Re:Decorators in Go using embedded structs
by weberc2 on Wednesday October 23, 2019 @05:11PM
(#21339064)
Both types implement the `Client` interface. So either type can be passed into a function that accepts the `Client` interface, but a `CachedHTTPClient` cannot be passed into a function that accepts an `HTTPClient` (you would have to pass the `CachedHTTPClient.HTTPClient`) and of course not vice versa either. You can do the same thing in Java (forgive my syntax):
[ Parent
| on HN ]
Re:Decorators in Go using embedded structs
by jayd16 on Wednesday October 23, 2019 @11:06PM
(#21341310)
Makes sense. I guess I just don't see how exported types save you from any of the pitfalls of inheritance. In my mind composition is the use of existing types without being forced into a type contract.
Re:Decorators in Go using embedded structs
by weberc2 on Thursday October 24, 2019 @01:36PM
(#21347027)
Mind you, I don’t advocate for struct embedding, but it doesn’t force you into a type contract. The outer struct retains its type—it is not a subtype of the nested type so it can’t be used in places that take the inner type.
Literally all it does is automatically create methods on the outer struct that delegate to the anonymous member.
Unlike inheritance, there is no fragile base class problem and methods on the inner anonymous member can’t dispatch to methods on the outer struct. Also, the “parent” member is just another field in your struct. You can modify it or replace it at runtime, unlike the parent in OOP languages.