我有这段代码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我对循环底部的第二个 Println 的问题。如果你运行它,你会看到它打印出 &[values...]。为什么不打印地址?我知道你可以用 Printf 等方法来做到这一点,而且它有效,但是 Println 呢?带有 &slice[0] 的 Println 工作正常,它打印地址而不是值,但是带有 &slice 的 Println 就像不一样。我也刚刚注意到,当我使用 &slice 执行 Printf 语句 %p 时,然后我只执行切片,我得到不同的地址。为什么?并且带有 &slice 的地址在更改时不会更改(运行它,程序会调整数组大小并创建一个新切片)。但是 printf(%p, slice) 确实改变了?
1 回答
- 1 回答
- 0 关注
- 148 浏览
添加回答
举报
0/150
提交
取消