Middle+
What is the internal structure of interfaces in Go?
sobes.tech AI
Answer from AI
In Go, an interface is a pair: a pointer to data and a pointer to a method table.
// Conditional structure of an interface (not explicitly present in Go code)
type iface struct {
data uintptr // Pointer to the value
itab *itab // Pointer to the type and method table
}
// Conditional structure of a method table (also not explicitly present)
type itab struct {
inter *interfaceType // Pointer to the interface type
typ *_type // Pointer to the concrete type implementing the interface
hash uint32 // Hash for faster lookup
_ [4]byte // Padding
fun [1]uintptr // Array of pointers to methods. Actual size depends on the number of methods.
}
data: Stores a pointer to the actual value that implements the interface. If the value is a pointer type,datapoints to the pointer itself. If the value is not a pointer type (e.g.,int,string), it can be copied or stored in a separate structure pointed to bydata. Small values may be stored directly indata.itab: Pointer to the method table for a specific interface/type pair. This table is created upon the first conversion of a concrete type to this interface or at compile time for known type/interface pairs.
When an interface method is called, Go uses itab to find the correct function (method) for the called type and invokes it, passing data as the receiver.
Key points:
- Go does not require explicit declaration of interface implementation. Checking occurs at runtime or statically at compile time.
itabis cached, which speeds up subsequent calls to the same interface methods for the same type.- Interfaces in Go are "thin" (non-fat pointers) compared to their counterparts in some other languages, which contributes to performance.
- An empty interface (
interface{}) hasitabequal to nil because it has no methods, only a pointer to data (data).