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+) insteadInterface 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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
