你为什么要用golang的作文? [英] Why would you want to use composition in golang?

查看:106
本文介绍了你为什么要用golang的作文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



为什么你会想在golang中使用组合?

  type obj1Inherited struct {
obj2
}

类型obj1构造结构{
someobj obj2
}

类型obj2结构体{
}

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

func main(){
o:= obj1Inherited {}
o .printTest()//罚款 - printTest被提升

obj1Composed:= obj1Composed {}
obj1Composed.selector.printTest()//很好,因为我使用了合成的obj
obj1Composed.printTest()// not fine - printTest is not promote


解决方案

值得关于 Eff中关于嵌入的部分

一个常见的例子是使用一个带有Mutex的struct / map。

 类型SafeStruct struct {
SomeField字符串
* sync.Mutex
}

输入

  safe:= SafeStruct {SomeField:init ()
safe.Unlock()
safe.SomeField =新值

比编写适当的包装函数(这是重复的)或者

  safe.mutex.Unlock()

在这种情况下,访问方法( Lock() Unlock() / p>

当您尝试在嵌入字段中使用多个函数时(这会实现像 io.ReadWriter )。


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

解决方案

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).

这篇关于你为什么要用golang的作文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆