普通网友 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 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值