Golang / Golang Internals and Memory Management Interview Questions
How are Go interfaces implemented internally and why do they matter for performance?
A Go interface value is a two-word struct: a type pointer and a data pointer. There are two variants in the runtime: iface (for interfaces with methods — has a pointer to the method table / itab) and eface (for the empty interface any — just type and data pointers).
// Empty interface (any / interface{}) // eface { type *_type, data unsafe.Pointer } var v any = 42 // _type = pointer to int's type descriptor // data = pointer to a heap-allocated int holding 42 // Interface with methods // iface { itab *itab, data unsafe.Pointer } // itab = {inter *interfacetype, type *_type, hash uint32, fun [...]uintptr} // fun[] = the method dispatch table (virtual call table) type Stringer interface { String() string } type MyInt int func (m MyInt) String() string { return fmt.Sprintf("%d", m) } var s Stringer = MyInt(5) // iface{itab=*MyInt-Stringer-itab, data=ptr-to-5} fmt.Println(s.String()) // dispatches via itab.fun[0] // Type assertion â recovers the concrete type if mi, ok := s.(MyInt); ok { fmt.Println(mi + 1) } // Type switch switch t := v.(type) { case int: fmt.Println("int:", t) case string: fmt.Println("string:", t) default: fmt.Println("unknown") } // Performance implication: values stored in interface often escape to heap // Small values (pointer-sized or smaller) can be inlined into the data word // Avoid interface{} in hot paths â use generics (Go 1.18+) instead
Interface comparison: two interface values are equal if and only if their type pointers are equal (same concrete type) and their data pointers point to equal values. Comparing interfaces with non-comparable concrete types (e.g., slices) panics at runtime.
Nil interface pitfall: (*MyType)(nil) stored in an interface is not a nil interface — the interface has a non-nil type pointer. Always return a nil interface (return nil) rather than a typed nil pointer when returning an interface from a function.
More Related questions...