Inheritance and Subtyping
9 comments
·January 29, 2025grey-area
Go interfaces are explicit, not implicit, the difference is more where they are defined.
With subtypes the interfaces are defined with classes(an animal does this and that), with interfaces they are defined at the point of use (I accept a param that does this and that).
Interesting that gosling said at one point he felt including classes (i.e. inheritance) in Java was a mistake. I feel this is one thing Go got right compared to many other languages. Turns out inheritance just isn’t very helpful.
Jtsummers
> Go interfaces are explicit, not implicit, the difference is more where they are defined.
That's not what the blog author wrote so what are you responding to? What they actually wrote:
>> If a Go struct implements the same functions as an interface, it implicitly implements the interface.
And that's correct except they use the term "functions" instead of "methods". But most people won't get confused by that distinction.
https://go.dev/tour/methods/10 - "Interfaces are implemented implicitly"
grey-area
They are declared explicitly and implemented implicitly.
Thus the analogy the author is trying to make with magic methods in more dynamic languages like python or ruby is inaccurate and IMO misleading.
pfdietz
> Python is the most interesting language I know of regarding inheritance.
Someone doesn't know Common Lisp.
marginalia_nu
I don't think subtyping is something you should probably be using very often. I wouldn't say never, but you can go a very long time without finding a legitimate use for the feature, and your code will generally be better for it.
It's a bit weird, given how these elaborate class hierarchies were touted as such a big and important feature in Java originally, but when the dust settled it turned out more often than not to complicate the code.
cobbal
Personally I like to differentiate subclassing from conforming to an interface. Both are subtyping, but interfaces are much cleaner.
marginalia_nu
Interface inheritance is indeed much less of a foot-gun than class inheritance, but I'll argue even interfaces are generally fairly overused. The single-class interface pattern that exists in some parts of Java-land is just bizarre.
null
I think this is interesting, but I think the way Python is described is slightly wrong? In Python, you don't need to define a protocol to support duck typing, you can just implement the same behavior. Protocols don't have a function outside of static typing (they don't influence any program behavior at run-time.)
I guess it depends on whether you consider duck typing to be "passes the static type checker" or "it works the same".