Go slices as reference to arrays
A slice does not store any data, it just describes a section of an underlying array.
Changing the elements of a slice modifies the corresponding elements of its underlying array.
Other slices that share the same underlying array will see those changes.
1package main
2
3import "fmt"
4
5func main() {
6 names := [4]string{
7 "John",
8 "Paul",
9 "George",
10 "Ringo",
11 }
12 fmt.Println(names)
13
14 a := names[0:2]
15 b := names[1:3]
16 fmt.Println(a, b)
17
18 b[0] = "XXX"
19 fmt.Println(a, b)
20 fmt.Println(names)
21}
22
23// Output
24// [John Paul George Ringo]
25// [John Paul] [Paul George]
26// [John XXX] [XXX George]
27// [John XXX George Ringo]
References
Next -> slice-zero-value
Next -> creating-a-slice-with-make