5 ms·
Does anybody know how Go manages to call the given function of the matching interface when it gets only a pointer to the struct? Like here, where label and butt
by acqq 14y ago
Does anybody know how Go manages to call the given function of the matching interface when it gets only a pointer to the struct? Like here, where label and button are otherwise unrelated structs but both have the same Paint function:
for _, painter := range []Painter{label, listBox, button1, button2} {
painter.Paint()
}
In C++, where inheritance is used, the virtual function pointer tables are maintained and the inherited class will have the function at the same index which makes calls of virtual functions slower than normal calls but the cost is still just an indexing of the table. However when there is no inheritance specification, the indexes can't be maintained, I presume. The easy solution is that calls are resolved using some string fingerprint lookup but that would make such calls really slow (compared to the C++).
Then how do they do it?
- MHordecki 14y agoI remember I've studied this a while back, but the exact answer eludes me. I suppose they use techniques akin to what JVM uses (see [1]). [1] www.research.ibm.com/people/d/dgrove/papers/oopsla01.pdf
- nyan_sandwich 14y agoIt doesn't get a pointer to the struct, it gets an object that implements whatever interface. At least that's the story from the type system perspective. Given that, it seems easy enough to just pass a {pointer, vtable} value. In C++ (if I understand correctly) each object/class has one vtable. In Go, it seems that each type has as many vtables as are needed for the contexts it's called in. See also type classes in haskell. (this is all guessing. Someone please call me out if I'm wrong)
- ralph 14y agoThis post by rsc should answer your questions and more. http://research.swtch.com/interfaces http://research.swtch.com/interfaces
- acqq 14y agoThanks, it seems it fully answers my question!
- deleted 14y ago[deleted]