Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

So Go has embedding not inheritance because SubClass is not an instance of SuperClass, there is no hierarchy, only composition.

BUT what you might not realize is that any method defined on SuperClass (and only defined on SuperClass) can be called on SubClass, but it operates on SuperClass data. This allows SubClass to use SuperClass to help it fulfil an interface for example.

See it in action: http://play.golang.org/p/8kiwu1PlW_



This is similar to C++ in which base class methods are 'virtual'. Is there a way to stop this behaviour? Just thinking how non-virtual methods can be implemented then. C++ has a keyword, 'virtual', for switching this behaviour, but any analogue in Go?


You mean like final in Java? I don't believe there is. Go has a different way of handling OO and so far I have never needed "final". In Go embedding is not common and interfaces are used much more.

In Go, having final in an embedded struct affect the containing struct seems wrong IMHO- this would allow embeded fields to dictate the behaviour of things that embed them. I don't think most programmers would be happy with adding a field to a struct and as a consequence be prevented from implementing a given method signature.


Ah sorry, I have no idea about Java or final, so ... can't comment.





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: