1

What is the difference between go's type embedding and object composition?

My understanding is that type embedding is object composition except the methods of the embedded type are automatically forwarded as they would be in inheritance.

4

It's exactly as you described it: Go's embedding is composition with the added benefit of "forwarding" the interface.

In my mind embedding is an attempt to preserve the main benefit of traditional OOP inheritance--code reuse--while avoiding its greatest pitfall--extremely tight coupling. When you "inherit" a method via embedding, your "derived" class is not responsible for or even capable of reimplementing it, so it can't possibly "break the base class" somehow. And, since there are no "protected" or "private" methods that your "derived" class might gain access to, there's no violation of encapsulation. But you still have all the convenience of directly "inheriting" the "base class interface" as opposed to writing a bunch of wrapper functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.