我在C中有一些exp,而且我对golang来说是全新的
func learnArraySlice() {
intarr := [5]int{12, 34, 55, 66, 43}
slice := intarr[:]
fmt.Printf("the len is %d and cap is %d \n", len(slice), cap(slice))
fmt.Printf("address of slice 0x%x add of Arr 0x%x \n", &slice, &intarr)
}
现在golang slice是一个数组的引用,它包含指向切片数组len和切片上限的指针,但是这个切片也将在内存中分配,我想打印该内存的地址。但无法做到这一点。
答案 0 :(得分:26)
fmt.Printf("address of slice %p add of Arr %p \n", &slice, &intarr)
%p
会打印地址。
答案 1 :(得分:10)
切片及其元素是可寻址的:
s := make([]int, 10)
fmt.Printf("Addr of first element: %p\n", &s[0])
fmt.Printf("Addr of slice itself: %p\n", &s)
答案 2 :(得分:4)
对于切片底层数组和数组的地址(在您的示例中它们是相同的),
package main
import "fmt"
func main() {
intarr := [5]int{12, 34, 55, 66, 43}
slice := intarr[:]
fmt.Printf("the len is %d and cap is %d \n", len(slice), cap(slice))
fmt.Printf("address of slice %p add of Arr %p\n", &slice[0], &intarr)
}
输出:
the len is 5 and cap is 5
address of slice 0x1052f2c0 add of Arr 0x1052f2c0