Object-Oriented Inheritance in Go

  • This is not inheritance, but rather embedding. A form of composition. Go does not have inheritance.

    https://golang.org/doc/effective_go.html#embedding

  • 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.

  • > 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.

  • 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

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

    Think of it as language-assisted copy paste.

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