我有這段代碼package mainimport ( "fmt")func Extend(slice []int, element int) []int { n := len(slice) if n == cap(slice) { // Slice is full; must grow. // We double its size and add 1, so if the size is zero we still grow. newSlice := make([]int, len(slice), 2*len(slice)+1) copy(newSlice, slice) slice = newSlice } slice = slice[0 : n+1] slice[n] = element return slice}func main() { slice := make([]int, 0, 5) for i := 0; i < 10; i++ { slice = Extend(slice, i) fmt.Printf("len=%d cap=%d slice=%v\n", len(slice), cap(slice), slice) fmt.Println("address of 0th element:", &slice[0]) fmt.Println("address of slice:", &slice) // why does this print the slice and not its address? fmt.Printf("address of slice: %p\n", &slice) // why is this different from below? and why does it not change when a new slice is created pointing to a different array? fmt.Printf("address of slice: %p\n\n", slice) }}游樂場:https : //play.golang.org/p/PWMN-i9_z9我對(duì)循環(huán)底部的第二個(gè) Println 的問題。如果你運(yùn)行它,你會(huì)看到它打印出 &[values...]。為什么不打印地址?我知道你可以用 Printf 等方法來做到這一點(diǎn),而且它有效,但是 Println 呢?帶有 &slice[0] 的 Println 工作正常,它打印地址而不是值,但是帶有 &slice 的 Println 就像不一樣。我也剛剛注意到,當(dāng)我使用 &slice 執(zhí)行 Printf 語句 %p 時(shí),然后我只執(zhí)行切片,我得到不同的地址。為什么?并且?guī)в?&slice 的地址在更改時(shí)不會(huì)更改(運(yùn)行它,程序會(huì)調(diào)整數(shù)組大小并創(chuàng)建一個(gè)新切片)。但是 printf(%p, slice) 確實(shí)改變了?
- 1 回答
- 0 關(guān)注
- 166 瀏覽
添加回答
舉報(bào)
0/150
提交
取消