普通网友 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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?