普通网友 2019-07-27 23:35
浏览 78
已采纳

将struct vs指针嵌入到用作指针的struct中

If I have a struct type A which is used as a pointer (has pointer receivers only, the constructor returns *A, etc.), what is the difference between embedding a struct type B as B versus *B?

That is, what is the difference between

type B struct {...}
type A struct {
    B
    // ...
}

and

type B struct {...}
type A struct {
    *B
    // ...
}

For example, is there ever copying of the embedded field?

Edit: I should also mention that the embedded struct B only has pointer receivers.

  • 写回答

2条回答 默认 最新

  • dongshi1102 2019-07-28 00:13
    关注

    The zero values of the two structures are different, which can be a significant ergonomic difference.

    Consider an embedded type

    type B struct {
        X int
    }
    
    func (b *B) Print() { fmt.Printf("%d
    ", b.X) }
    

    If we embed this directly as an object

    type AObj struct {
        B
    }
    

    then the zero value of type AObj includes an embedded object of type B, which also has its zero value, and therefore we can safely

    var aObj AObj
    aObj.Print() // prints 0
    

    But if we instead embed a pointer

    type APtr struct {
        *B
    }
    

    the zero value of this struct has a nil pointer value, and we can't really use it directly.

    var aPtr APtr
    aPtr.Print() // panics
    

    Objects get copied in hopefully the way you might expect. If you create a new AObj object, it gets a copy of the embedded B.

    aObj2 := aObj
    aObj.X = 1
    aObj2.Print() // prints 0, because it has a copy
    

    If you create a new APtr object, it gets a copy of the *B, which means it shares the underlying concrete object.

    aPtr.B = &B{}
    aPtr2 := aPtr
    aPtr.X = 1
    aPtr2.Print() // prints 1, because both objects point at the same B
    

    Runnable example at https://play.golang.org/p/XmOgegwVFeE

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用