Hacker News new | ask | show | jobs
by justinsb 4040 days ago
It looks more like inheritance: the methods on net.Conn & io.Writer are automatically exposed. Are you saying that it is composition because you are "inheriting" from interfaces, which isn't traditional inheritance? Or if not, can you explain why you think of this as composition and not inheritance?

Edit: On further thought, this looks to me like composition with automatic delegation (a huge productivity benefit of inheritance). It is unusual because the combined class also implements the interfaces because of Go's interface rules, but I think that the late-binding to implementations is more similar to composition.

2 comments

The inner structs (of which the outer writer struct is composed) cannot access any of the functionality or fields outside of itself. Each inner struct is completely encapsulated, so you can't override an inner struct method and expect the inner struct's behavior to change.

The accessibility of inner struct methods from the outer struct is a syntactic convenience.

Java: https://gist.github.com/jaekwon/8025b9f3a482b3219a21 Go: https://gist.github.com/jaekwon/0f6e5555ab6a592aa4c8

Once you Go, you never go back. ;)

There are also no virtual methods with struct composition. If B embeds A, "upcasting" an instance of B to A will not allow you to call any methods on B.
This is not inheritance, careful about what you say here since it is totally misleading. while embedding structs is useful in a lot of cases, it might yield unexpected results if you expect embedding to work "more like inheritance".

ex

    type A struct{}
  
    func (a *A)GetSelf()*A{return a}

    type B struct{ A }

    b:=&B{A{}}

b.GetSelf() returns type A , not type B

It gets even more confusing when you start embedding interfaces in structs.