你为什么要用golang的作文? [英] Why would you want to use composition in 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。 输入 比编写适当的包装函数(这是重复的)或者 在这种情况下,访问方法( 当您尝试在嵌入字段中使用多个函数时(这会实现像 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?
It is worth going over the section on Embedding in Effective Go. A common example is having a struct/map with a Mutex. It is much easier to type than having to either write appropriate wrapper functions (which are repetitive) or have the stutter of when the only thing you would ever do with the mutex field is access the methods ( This becomes even more helpful when you are trying to use multiple functions on the embedded field (that implemement an interface like 这篇关于你为什么要用golang的作文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
类型SafeStruct struct {
SomeField字符串
* sync.Mutex
}
safe:= SafeStruct {SomeField:init ()
safe.Unlock()
safe.SomeField =新值
safe.mutex.Unlock()
Lock()
和 Unlock()
/ p>
io.ReadWriter
)。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
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()
and Unlock()
in this case)io.ReadWriter
).