2019-06-05 20:34
浏览 72


How can I get the memory address of an embedded slice in a struct?


type t1 struct {
    data string

type t2 struct {
    listData []t1

Now I want to know the memory address of listData. I couldn't figure out how to get the memory address out of it using the following:

newData := t2{}
newData.listData = append(newData.listData, t1{data:"mydata"})
printf("%p", &newData.listData) // this doesn't work, in fact it returns address of newData
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doulao1934 2019-06-05 20:38

    listData is the first field in the struct, its memory offset relative to the struct's address is zero, so they have the same address.

    type t2 struct {
    listData []string
    moreData []int
    func main() {
        var foo t2
        fmt.Printf("%p %p %p", &foo, &foo.listData, &foo.moreData)

    0x43e260 0x43e260 0x43e26c

    解决 无用
    打赏 举报

相关推荐 更多相似问题