Hacker Timesnew | past | comments | ask | show | jobs | submitlogin
Object-Oriented Inheritance in Go (hackthology.com)
13 points by timtadh on May 20, 2016 | hide | past | favorite | 7 comments


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

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


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.


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.


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!


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




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: