Slices
Go slice and Python slice have very similar syntax, but Python slice is a shallow copy of part of the original list, while Go slice is just a new range within the same underlying array of the original slice.
Let’s try:
a = [1, 2, 3]
b = a[:2]
b[0] = 9
print(a)
print(b)
# output:
# [1, 2, 3]
# [9, 2]
See a[0]
remains the same.
package main
import (
"fmt"
)
func main() {
a := []int{1, 2, 3}
b := a[:2]
b[0] = 9
fmt.Println(a)
fmt.Println(b)
# output:
# [9 2 3]
# [9 2]
}
See a[0]
changes because slice a
and b
shares the same underlying array.