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).
More Related questions...