dongzaocheng3214 2016-04-18 21:22
浏览 117
已采纳

为什么要在golang中使用组合?

In the following code I show what I think is the difference between embedding (where methods get promoted) and composition (where methods are not promoted) in golang.

Why would you ever want to use composition in golang?

type obj1Inherited struct {
    obj2
}

type obj1Composed struct {
    someobj obj2
}

type obj2 struct {
}

func (o obj2) printTest() {
    fmt.Println("obj2")
}

func main() {
    o := obj1Inherited{}
    o.printTest() //fine - printTest is promoted

    obj1Composed := obj1Composed{}
    obj1Composed.selector.printTest() //fine because I'm using the composed obj
    obj1Composed.printTest() //not fine - printTest is NOT promoted
  • 写回答

1条回答 默认 最新

  • doutu6658 2016-04-18 23:50
    关注

    It is worth going over the section on Embedding in Effective Go.

    A common example is having a struct/map with a Mutex.

    type SafeStruct struct {
        SomeField string 
        *sync.Mutex
    }
    

    It is much easier to type

    safe := SafeStruct{SomeField: "init value"}
    
    safe.Lock()
    defer safe.Unlock()
    safe.SomeField = "new value"
    

    than having to either write appropriate wrapper functions (which are repetitive) or have the stutter of

    safe.mutex.Unlock()
    

    when the only thing you would ever do with the mutex field is access the methods (Lock() and Unlock() in this case)

    This becomes even more helpful when you are trying to use multiple functions on the embedded field (that implemement an interface like io.ReadWriter).

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

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?