Slices are like references 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.

slices-pointers.go

  1. package main
  2. import "fmt"
  3. func main() {
  4. names := [4]string{
  5. "John",
  6. "Paul",
  7. "George",
  8. "Ringo",
  9. }
  10. fmt.Println(names)
  11. a := names[0:2]
  12. b := names[1:3]
  13. fmt.Println(a, b)
  14. b[0] = "XXX"
  15. fmt.Println(a, b)
  16. fmt.Println(names)
  17. }