
Object-Oriented Inheritance in Go - timtadh
http://hackthology.com/object-oriented-inheritance-in-go.html
======
echlebek
This is not inheritance, but rather embedding. A form of composition. Go does
not have inheritance.

[https://golang.org/doc/effective_go.html#embedding](https://golang.org/doc/effective_go.html#embedding)

~~~
timtadh
Author Here: Good point. I had forgotten that the effective go document had a
section on it. I will add the link. My main point is that Go embedding can be
used as a form of subclassing allowing types to share, code, data or both.

------
lobster_johnson
The section "Inheriting from structs" is misleading. It's embedding, not
inheriting. A big different is that it does not lead to type compatibility.
Given this:

    
    
        type Foo struct {
          ...
        }
    
        type Bar struct {
          Foo
        }
    

...You can't pass Bar (or pointer to Bar) to anything that requires Foo (or
pointer to Foo), even it looks like they'd have identical memory layouts and
therefore be compatible, though that is exactly what inheritance aims to
achieve in other OO languages.

~~~
timtadh
Good point and definitely an annoying limitation. The work around is to use an
interface as the expected type as I do in the lexing example.

I should have included a section on the limitations of embedding. This is what
happens when I don't stew on the writing for a day or two before putting it
out there! I will have to make a pass through the article and clear up the
terminology. Thanks for the feedback!

------
spriggan3
> It turns out we can use Go's built in support for inheritance to avoid this
> work.

There is no support for inheritance in Go, calling struct embedding
inheritance is incorrect. Inheritance implies a type hierarchy, there is no
type hierarchy in Go, types are flat. If you think you can mimick inheritance
with struct embedding you're going to feel a whole lot of pain when you pass
values around functions then expect boxing / unboxing types to work in like C#
or Java.

------
breerly
I object to the use of the term "inheritance" here.

It's a bit more like PHP's traits -
[https://secure.php.net/manual/en/language.oop5.traits.php](https://secure.php.net/manual/en/language.oop5.traits.php)

Ruby's mixins are a bit similar as well -
[http://culttt.com/2015/07/08/working-with-mixins-in-
ruby/](http://culttt.com/2015/07/08/working-with-mixins-in-ruby/)

Think of it as language-assisted copy paste.

------
timtadh
Thanks everyone for your feedback. I improved the post to discuss limitations
of embedding and some workarounds.

