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

查理:

在下面的代码中,我展示了我认为在golang中嵌入(提升方法的位置)和组合(提升方法的位置)之间的区别。

为什么您要在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
matt.s:

值得阅读有关“嵌入到有效Go中”的部分

一个常见的示例是具有Mutex的结构/映射。

type SafeStruct struct {
    SomeField string 
    *sync.Mutex
}

打字容易得多

safe := SafeStruct{SomeField: "init value"}

safe.Lock()
defer safe.Unlock()
safe.SomeField = "new value"

而不是必须编写适当的包装器函数(重复的)或遇到困难

safe.mutex.Unlock()

当你将永远做互斥领域的唯一事情就是访问方法(Lock()Unlock()在这种情况下)

当您尝试在嵌入式字段上使用多种功能(实现像这样的接口io.ReadWriter时,这将变得更加有用

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章