3 ms·
In my opinion the interface system in Go is largely redundant, because interfaces are mostly equivalent to… structs of function pointers. And the single functio
by kubb 3y ago
In my opinion the interface system in Go is largely redundant, because interfaces are mostly equivalent to… structs of function pointers. And the single function interface case is just equivalent to a single function pointer.
If Go had a slightly better syntax for that, a lot of the interface use cases could be largely simplified. The interface implementation as subtype could be replaced with explicit instantiation using an “extends” keyword, plus sum types, and it would have been a simpler approach.
- MrBuddyCasino 3y agoNot sure I get it. Can you post some source code as an example?
- benhoyt 3y agoHere's one possibility. With an interface: https://go.dev/play/p/WTo2k_7PeRT https://go.dev/play/p/WTo2k_7PeRT type Barker interface { Name() string Bark() } And with a function-struct: https://go.dev/play/p/A_p40q1ARyR https://go.dev/play/p/A_p40q1ARyR type Barker struct { Name func() string Bark func() }
- benhoyt 3y ago> interfaces are mostly equivalent to… structs of function pointers This is an interesting discussion point. Some colleagues at a previous workplace actually used such structs with function fields (in Go they're not designated "function pointers") and ended up with what I called "poor man's interfaces". They're awkward to use, though in some ways they're more flexible, as you can mix and match implementations by changing any of the function fields. However, interfaces are much smaller: only two words. Imagine if you had a 20-method function-struct and then a slice of 1000 of those. With interfaces, that would be 2000 words, with functions-structs it'd be 10x that big. (I suspect interface methods are faster to call, too.) So apart from interfaces having more first-class language support, I suspect performance is one of the reasons they weren't done this way.
- nine_k 3y agoAll it takes is a pointer to some prototype struct shared by all instances; let's call it VMT. Congrats, we have reinvented canonical OOP classes, in their crudest form, and without any syntax sugar. We can still make the type system give us some static guarantees for presence of the methods, and maybe the compatibility between methods we put into slots, and instances they'll have to operate on. We're on the way of inventing ObjC, JavaScript, or C++, depending on how bad our tastes are %)
- pjmlp 3y agoSomeone just rediscoverd Oberon as originally designed in 1987! Extensible records with function pointers.
- cowl 3y ago> The interface implementation as subtype could be replaced with explicit instantiation using an “extends” keyword, plus sum types, and it would have been a simpler approach. Sure if you want to remove one of the better features of Go, Implicit interface implementation.