Go Slice Operations
Slice operations change or check the items in a slice. Append adds items, copy duplicates them, and Equal compares two slices.
Append a whole slice
Append first adds one item on its own. Three dots then spread a second slice into the append call.
package main
import "fmt"
func main() {
nums := []int{1, 2}
nums = append(nums, 3)
fmt.Println(nums)
extra := []int{4, 5}
nums = append(nums, extra...)
fmt.Println(nums)
}Copy a slice
Copy duplicates the items into a fresh slice. A later change to the original leaves the copy alone.
package main
import "fmt"
func main() {
src := []int{1, 2, 3}
dst := make([]int, len(src))
copy(dst, src)
src[0] = 99
fmt.Println(dst)
fmt.Println(src)
}Compare two slices
Equal reports whether two slices hold the same items in the same order. The second pair differs in the last item.
package main
import "fmt"
import "slices"
func main() {
a := []int{1, 2, 3}
b := []int{1, 2, 3}
c := []int{1, 2, 4}
fmt.Println(slices.Equal(a, b))
fmt.Println(slices.Equal(a, c))
}Delete the middle item
The idiom appends the tail onto the front part. The item at index 1 drops out.
package main
import "fmt"
func main() {
nums := []int{10, 20, 30, 40}
nums = append(nums[:1], nums[2:]...)
fmt.Println(nums)
}Example
package main
import "fmt"
func main() {
songs := []string{"Sun", "Moon"}
fmt.Println(songs)
songs = append(songs, "Stars")
fmt.Println(songs)
songs = append(songs[:0], songs[1:]...)
fmt.Println(songs)
}Key points
- The three dots after a slice spread its items into an append call.
- Use copy to duplicate items into another slice.
- A copy holds its own items after the copy runs.
- Use slices.Equal to test whether two slices match.
- The delete idiom appends the tail of a slice onto its front part.
In this example, songs starts with two titles. Append adds Stars at the end, and the slice prints with three titles. The delete idiom then drops the first title. The last print line shows the two titles that remain.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
What does copy(dst, src) do?