3

I have read this article which indicates a double tuple structure, but it is unfortunately light on implementation details, which is what I am looking for.

So... how are interfaces implemented in Go?

Pure guesswork on my part:

  • It cannot be a v-table in the C++ sense, because the interface is implicit - a struct doesn't know it conforms to an interface when compiled, only when passed to a function taking an interface does this actually happen.
  • I don't think it can be static polymorphism - every function that takes an interface parameter would have to be compile-time aware of every type that might be passed to it and I don't think that's true either.

What else is left?

user
  • 111
SRNissen
  • 161

1 Answers1

2

In Swift, there are (kind of) objects that represent interfaces. Say an interface has three functions. Then the interface object has three function pointers and a bit of storage. When you pass an object to a function expecting an interface, an interface object is created, three function pointers are stored, and the data is stored. I think (from memory) that for class instances a reference is stored, for small structs the contents of the struct, and for large structs a pointer is allocated.

Sounds a reasonable way to do this, so Go might do the same. You can convert such an object back to the original type if you know the type. A function using the interface object needs no knowledge of the actual type. Called an “existential interface”, so an interface that actually exists as an object.

gnasher729
  • 49,096