- Slices are similar to references to arrays. Changing elements in the underlying array modifies the elements of the slice. Changing the elements of a slice also modifies the elements of its underlying array, and the slices that share the underlying array with it observe these changes.
Click to view code
package main
import "fmt"
func main() {
names := [4]string{
"John",
"Paul",
"George",
"Ringo",
}
(names) // [John Paul George Ringo]
a := names[0:2]
b := names[1:3]
(a, b) // [John Paul] [Paul George]
names[1] = "gyt"
(a, b) // [John gyt] [gyt George]
(names) // [John gyt George Ringo]
}
- The length and capacity of the slice. The length of a slice is the number of elements it contains. The capacity of a slice is the number of elements counted from its first element to the end of its underlying array. Slicing a slice is slicing the underlying array again, in other words, slicing the capacity instead of the length. The capacity of a slice changes when the left boundary of the slice is set to a number greater than 0. Otherwise, the capacity does not change.
Click to view code
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s) // len=6 cap=6 [2 3 5 7 11 13]
s = s[:0]
printSlice(s) // len=0 cap=6 []
s = s[:4]
printSlice(s) // len=4 cap=6 [2 3 5 7]
s = s[1:4]
printSlice(s) // len=3 cap=5 [3 5 7]
s = s[2:]
printSlice(s) // len=1 cap=3 [7]
}
func printSlice(s []int) {
("len=%d cap=%d %v\n", len(s), cap(s), s)
}