如何在Golang中打印切片的内存地址?

问题描述 投票:16回答:3

我有一定的C语言经验,对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中是array的引用,其中包含指向slice的数组len和slice的上限的指针,但是该slice也将分配在内存中,我想打印该内存的地址。但无法做到这一点。

go slice memory-address
3个回答
30
投票

http://golang.org/pkg/fmt/

fmt.Printf("address of slice %p add of Arr %p \n", &slice, &intarr)

[%p将打印地址。


10
投票

切片及其元素是可寻址的:

s := make([]int, 10)
fmt.Printf("Addr of first element: %p\n", &s[0])
fmt.Printf("Addr of slice itself:  %p\n", &s)

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
© www.soinside.com 2019 - 2024. All rights reserved.