Why would you 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.
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
).