![](/img/trans.png)
[英]go - Can't create copy of variable of type map[int]Struct in another variable by just assigning one variable to another
[英]Assigning a variable of reference type “slice” to another variable, why don't they change simultaneously?
anotherSlice := theSlice
anotherSlice = append(anotherSlice, newEle)
fmt.Println(len(anotherSlice) == len(theSlice))
此代碼段將輸出false
。 為什么?
以下是其他一些實驗:
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
沒有新元素的容量, append
函數會創建新切片並返回它。 從那以后,切片anotherSlice
和theSlice
是不同的 - 它們由單獨的數組支持。
重新切割長度較短的切片anotherSlice[:3]
對切片的原始容量沒有影響。
以下行:
anotherSlice = append(anotherSlice[:3], anotherSlice[4:]...)
削減第四(索引3)元素。 因為anotherSlice[:3]
具有容納anotherSlice[4:]
所有元素的能力,所以不會發生新的分配,因此兩個切片都被修改。
package main
import (
"fmt"
)
func main() {
x := []int{1, 2, 3, 4, 5, 6}
fmt.Println(cap(x[:3]) >= len(x[:3])+len(x[4:]))
y := append(x[:3], x[4:]...)
fmt.Println(x, y)
}
為什么一個切片的長度不跟隨另一個切片的長度變化的變化的答案與可能被復制和/或修改的底層存儲無關。
在Go中,記住切片是很重要的。 它是一個帶有長度字段,容量字段和指向數組的指針的結構。 某些操作會更改長度字段。 有些人改變了容量字段。 有些更改存儲在基礎數組中的數據。
如果一個人沒有掌握如何在語言中實現切片,就會出現各種混亂和錯誤以及浪費的機會。 一旦人們對切片的實現方式感到滿意,它們就非常易於使用,並且編譯器能夠理解切片的結構,可以編寫一些非常優雅且易於讀取的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.