1 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
我認(rèn)為您的問題是您混淆了數(shù)組和切片。
數(shù)組是固定長度的值列表。實(shí)際上,您的示例中沒有使用任何數(shù)組??梢酝ㄟ^以下幾種方法聲明數(shù)組:
arr1 := [3]int{1, 2, 3} // an array of 3 integers, 1-3
arr2 := [...]int{1, 2, 3} // same as the previous line, but we're letting
// the compiler figure out the size of the array
var arr3 [3]int // a zeroed out array of 3 integers
您正在使用切片。切片是對(duì)基礎(chǔ)數(shù)組的引用。有幾種分配新切片的方法:
slice1 := []int{1, 2, 3} // a slice of length 3 containing the integers 1-3
slice2 := make([]int, 3) // a slice of length 3 containing three zero-value integers
slice3 := make([]int, 3, 5) // a slice of length 3, capacity 5 that's all zeroed out
其他任何切片分配都只是復(fù)制對(duì)數(shù)組的引用。
現(xiàn)在我們已經(jīng)確定了,
arr := []int{1, 2, 3, 4, 5}
創(chuàng)建一個(gè)切片,該切片引用包含數(shù)字1-5的匿名基礎(chǔ)數(shù)組。
arr2 := arr
重復(fù)該引用-它不復(fù)制底層數(shù)組。因此,存在一個(gè)基礎(chǔ)數(shù)組和對(duì)其的兩個(gè)引用。這就是為什么在修改arr的內(nèi)容時(shí)arr2的內(nèi)容會(huì)更改的原因。他們引用相同的數(shù)組。
- 1 回答
- 0 關(guān)注
- 291 瀏覽
添加回答
舉報(bào)