Since I am interested in the function, I read several articles on the topic and combined it into several reference points.
The attachment
Function named "embedding". And he solves the problem with repeated methods. Basic syntax:
type Person struct { Name string } type Speaker struct {
Wrap and decoration
Yes, no OOP, but the code should be DRY anyway. The clearest way to think about this function is to wrap structures using methods. Thus, the surest way to describe anonymous fields is to use the decorator pattern (well known to Pythonistas).
func (a *Speaker) Introduce(){
Merge and override
We can also combine methods implemented in structures
func (s Speaker) Speak() string { return "Blah-blah" } type Den struct { // Combine Person and Speaker under Den struct Person Speaker } func (d Den) Speak() string { // Override Speak method only for Dennis return "I'm quit!" } func main() { den := Den{Person: Person{Name: "Dennis",}} mike := Speaker{Person: Person{Name: "Michael",}} fmt.Println(den.Introduce()) fmt.Println(den.Speak()) fmt.Println(mike.Introduce()) fmt.Println(mike.Speak()) }
Thus, we can avoid the implementation of each required method for each type.
Interfaces
Same thing with interfaces. But if several interfaces are combined, this means that we do not need to declare methods that have already been declared in the interfaces used.
Playground
Dennis Suratna Blog Article
Documents
source share