4 ms·
> interfaces are mostly equivalent to… structs of function pointers This is an interesting discussion point. Some colleagues at a previous workplace actually u
by 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 %)