Golang / Golang Internals and Memory Management Interview Questions
How do type assertions and type switches perform internally in Go?
Type assertions and type switches are used to recover the concrete type from an interface value. Their performance characteristics matter in hot paths because they involve pointer comparisons and potentially method table lookups.
// Single type assertion
var v interface{} = "hello"
// Panicking form — use only when you are certain of the type
s := v.(string) // panics if v is not a string
// Safe form — never panics
s, ok := v.(string) // ok=false if wrong type
if !ok {
// handle mismatch
}
// Type switch — more efficient than chained if assertions
// The compiler generates optimised comparison code
func describe(v interface{}) string {
switch x := v.(type) {
case int: return fmt.Sprintf("int: %d", x)
case string: return fmt.Sprintf("string: %q", x)
case bool: return fmt.Sprintf("bool: %v", x)
case []byte: return fmt.Sprintf("bytes: %d bytes", len(x))
default: return fmt.Sprintf("unknown: %T", x)
}
}
// Performance:
// Single type assertion: ~1-3 ns — pointer comparison on the type word
// Type switch with many cases: O(n) comparisons unless compiler optimises
// For hot paths with many types: use a map[reflect.Type]func() or generics
// Interface-to-interface assertion: also cheap (same mechanism)
type Stringer interface{ String() string }
var r io.Reader = os.Stdin
if s, ok := r.(Stringer); ok {
fmt.Println(s.String()) // os.File implements Stringer
}A type assertion compares the concrete type pointer stored in the interface's type word against the target type. For interface-to-interface assertions, the runtime checks whether the concrete type implements the target interface by looking up the appropriate itab. The cache of itab lookups makes repeated interface assertions amortised O(1).
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...
