Reference "Invalid"
Implements a function to delete slice last item
func rmLast(a []int) { fmt.Printf("[rmlast] the address of a is %p", a) a = a[:len(a)-1] fmt.Printf("[rmlast] after remove, the address of a is %p", a)}
After calling this function, it is found that the original slice has not changed
func main() { xyz := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} fmt.Printf("[main] the address of xyz is %p\n", xyz) rmLast(xyz) fmt.Printf("[main] after remove, the address of xyz is %p\n", xyz) fmt.Printf("%v", xyz) //[1 2 3 4 5 6 7 8 9]}
The results are printed as follows:
[main] the address of xyz is 0xc2080365f0[rmlast] the address of a is 0xc2080365f0[rmlast] after remove, the address of a is 0xc2080365f0[main] after remove, the address of xyz is 0xc2080365f0[1 2 3 4 5 6 7 8 9]
Here the slice pointer value is printed directly, because slice is a reference type, so the pointer values are the same, we replace the print slice address to see
func rmLast(a []int) { fmt.Printf("[rmlast] the address of a is %p", &a) a = a[:len(a)-1] fmt.Printf("[rmlast] after remove, the address of a is %p", &a)}func main() { xyz := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} fmt.Printf("[main] the address of xyz is %p\n", &xyz) rmLast(xyz) fmt.Printf("[main] after remove, the address of xyz is %p\n", &xyz) fmt.Printf("%v", xyz) //[1 2 3 4 5 6 7 8 9]}
Results:
[main] the address of xyz is 0xc20801e1e0[rmlast] the address of a is 0xc20801e200[rmlast] after remove, the address of a is 0xc20801e200[main] after remove, the address of xyz is 0xc20801e1e0[1 2 3 4 5 6 7 8 9]
This time you can see that slice is actually copying a copy of the slice as a function parameter, because slice itself is a pointer, so from a phenomenon, slice is a reference type.