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))
}
出力は以下のようなものです::
そしてここでは、他のいくつかの実験である
追加スライスanotherSlice
は、新しい要素のための能力を持っていないときはいつでも
5 5
7 7
5 6
Program exited.
私は長さを縮めるために何かを試しました、プロセスはポストで更新されます。それは収縮後、anotherSliceも容量を5に縮小したからですか? –