anotherSlice := theSlice
anotherSlice = append(anotherSlice, newEle)
fmt.Println(len(anotherSlice) == len(theSlice))
这段代码将输出false
。为什么?将引用类型“slice”的变量赋值给另一个变量,为什么它们不同时变化?
这里有一些其他的实验:
package main
import "fmt"
func main() {
theSlice := []int{3,3,2,5,12,43}
anotherSlice := theSlice
fmt.Println(anotherSlice[3], theSlice[3])
anotherSlice[3] = anotherSlice[3]+2
fmt.Println(anotherSlice[3], theSlice[3])
anotherSlice = append(anotherSlice[:3], anotherSlice[4:]...)
fmt.Println(len(anotherSlice),len(theSlice))
}
输出是象下面这样:
5 5
7 7
5 6
Program exited.
我试过别的东西来缩小长度,这个过程在帖子中更新。那是因为在缩小之后,anotherSlice'也缩小到了5? –