Golang / GoLang Interfaces and Object Oriented Interview Questions
What is the internal two-word structure of a Go interface value?
Internally, every non-empty interface value is a two-word pair stored on the stack (or heap if it escapes):
| Word | Name | Content |
|---|---|---|
| Word 1 | itab (type word) | Pointer to an itab struct containing: the interface type descriptor, the concrete type descriptor, a hash of the concrete type, and the method dispatch table (function pointers) |
| Word 2 | data (value word) | Pointer to the concrete value on the heap, or the value itself if it fits in one pointer and is pointer-shaped |
type Animal interface { Sound() string } type Dog struct{ Name string } func (d Dog) Sound() string { return "Woof" } var a Animal = Dog{Name: "Rex"} // Memory layout of 'a': // word1 â itab{itype=Animal, ctype=Dog, hash=..., fun=[Dog.Sound]} // word2 â *Dog{Name: "Rex"} (heap-allocated copy) // Nil interface â BOTH words are nil var a2 Animal // nil interface: word1=nil, word2=nil fmt.Println(a2 == nil) // true // Non-nil interface holding nil pointer â word1 is non-nil! var d *Dog a = d // word1 â itab{ctype=*Dog,...}, word2 â nil fmt.Println(a == nil) // FALSE â classic trap // Inspect with reflect import "reflect" v := reflect.ValueOf(a) fmt.Println(v.IsNil()) // true â the *Dog data pointer is nil fmt.Println(a == nil) // false â the interface itself is non-nil
The empty interface any (alias for interface{}) uses a simpler two-word layout called eface: word1 is a plain type pointer (no method table), word2 is the data pointer. Non-empty interfaces use iface with the full itab. The itab is cached globally per (interface type, concrete type) pair, so interface assignment is effectively free after the first occurrence.
More Related questions...