Golang / Golang Internals and Memory Management Interview Questions
How do generics work in Go 1.18+ and how do they affect performance?
Go 1.18 introduced type parameters (generics), allowing functions and types to be parameterised over types constrained by interfaces. Go uses a GCShape-based implementation: rather than generating a separate binary for each concrete type (full monomorphisation), Go creates a dictionary-based dispatch for types with the same GC shape (memory layout), reducing binary size at a small runtime cost.
// Generic function with type constraint func Min[T constraints.Ordered](a, b T) T { if a < b { return a } return b } fmt.Println(Min(3, 5)) // int fmt.Println(Min(3.14, 2.71)) // float64 fmt.Println(Min("foo", "bar")) // string // Generic type type Stack[T any] struct { items []T } func (s *Stack[T]) Push(item T) { s.items = append(s.items, item) } func (s *Stack[T]) Pop() (T, bool) { var zero T if len(s.items) == 0 { return zero, false } n := len(s.items) - 1 item := s.items[n] s.items = s.items[:n] return item, true } // Custom interface constraint type Number interface { ~int | ~int32 | ~int64 | ~float32 | ~float64 } func Sum[T Number](nums []T) T { var total T for _, n := range nums { total += n } return total } // ~ means: any type whose underlying type is int type MyInt int // ~int matches MyInt fmt.Println(Sum([]MyInt{1, 2, 3})) // 6
Performance: For pointer-sized types (interfaces, pointers, slices), Go generates a single implementation shared via a dictionary (like Java's type erasure). For value types (int, float64), Go can generate specialised code paths. In practice, generic functions are slightly slower than hand-written type-specific functions in some workloads but eliminate code duplication. Use generics when the algorithm is the same across types and the alternative is copy-paste or reflection.
More Related questions...