Last active
December 11, 2024 11:58
-
-
Save paulja/2e6537633a0f763e3f484cdcba047bd4 to your computer and use it in GitHub Desktop.
Slice operations in Go, classic and modern approaches
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"slices" | |
) | |
func main() { | |
classic() | |
modern() | |
} | |
func classic() { | |
vec := []int{1, 2, 3, 4} | |
fmt.Println("--- classic ---") | |
// add | |
vec = append(vec, 5) | |
fmt.Println(vec) | |
// remove the last item | |
vec = vec[:len(vec)-1] | |
fmt.Println(vec) | |
// remove from the middle | |
idx := 2 | |
vec = append(vec[:idx], vec[idx+1:]...) | |
fmt.Println(vec) | |
// append to the middle (insert) | |
vec = append(vec[:idx+1], vec[idx:]...) | |
vec[idx] = 3 | |
fmt.Println(vec) | |
} | |
func modern() { | |
vec := []int{1, 2, 3, 4} | |
fmt.Println("--- modern ---") | |
// add | |
vec = append(vec, 5) | |
fmt.Println(vec) | |
// remove the last item | |
vec = slices.Delete(vec, len(vec)-1, len(vec)) | |
fmt.Println(vec) | |
// remove from the middle | |
idx := 2 | |
vec = slices.Delete(vec, idx, idx+1) | |
fmt.Println(vec) | |
// append to the middle (insert) | |
vec = slices.Insert(vec, idx, 3) | |
fmt.Println(vec) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment