dpx49470 2014-08-10 10:13
浏览 22
已采纳

初始化嵌入式结构时的指针差异

I am playing around with struct embedding and have a problem with keeping the same reference to the embedded struct.

Try out Go Playground and see that there are two different pointer addresses to *strings.Reader.

package main

import (
    "fmt"
    "strings"
)

type Base struct {
    reader *strings.Reader
}

func NewBase() *Base {
    r := strings.NewReader("hello")

    fmt.Printf("document: %#+v

", &r)
    return &Base{r}
}

func (b *Base) Check() {
    fmt.Printf("document: %#+v

", &b.reader)

}

type Concrete struct {
    *Base
}

func NewConcrete() *Concrete {
    return &Concrete{NewBase()}
}

func main() {
    c := NewConcrete()
    c.Check()
}

Why are these addresses not the same? How do I fix this?

展开全部

  • 写回答

1条回答 默认 最新

  • douxian9060 2014-08-10 10:17
    关注

    You're checking the address of the pointer, not the pointer itself.

    func NewBase() *Base {
        r := strings.NewReader("hello")
    
        fmt.Printf("document: %#p
    
    ", r)
        return &Base{r}
    }
    
    func (b *Base) Check() {
        fmt.Printf("document: %#p
    
    ", b.reader)
    
    }
    

    <kbd>playground</kbd>

    //edit

    r := strings.NewReader("hello")
    

    r is a variable holding a pointer to strings.Reader, &r is the address of the variable holding the pointer to strings.Reader.

    fmt.Printf("document: %#+v
    
    ", &b.reader)
    

    &b.reader is the address of the variable b.reader, which is holding the pointer of the strings.Reader from earlier.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部