Golang / GoLang System Architecture and Testing Interview Questions
How do generics in Go 1.18+ enable better system design and what are the trade-offs?
Go generics allow writing type-safe, reusable data structures and algorithms without code duplication or losing type information through interfaces. The key use cases: generic data structures, result/option types, and typed collections.
// Generic Result type â eliminates panic-or-nil patterns type Result[T any] struct { value T err error } func Ok[T any](v T) Result[T] { return Result[T]{value: v} } func Err[T any](e error) Result[T] { return Result[T]{err: e} } func (r Result[T]) Unwrap() (T, error) { return r.value, r.err } func (r Result[T]) IsOk() bool { return r.err == nil } // Generic ordered set type Set[T comparable] struct { items map[T]struct{} } func NewSet[T comparable]() *Set[T] { return &Set[T]{items: make(map[T]struct{})} } func (s *Set[T]) Add(v T) { s.items[v] = struct{}{} } func (s *Set[T]) Has(v T) bool { _, ok := s.items[v]; return ok } func (s *Set[T]) Len() int { return len(s.items) } // Generic Map/Filter/Reduce â functional pipeline without reflect func Map[T, U any](slice []T, fn func(T) U) []U { result := make([]U, len(slice)) for i, v := range slice { result[i] = fn(v) } return result } func Filter[T any](slice []T, pred func(T) bool) []T { var result []T for _, v := range slice { if pred(v) { result = append(result, v) } } return result } // Usage users := []User{{ID: 1, Active: true}, {ID: 2, Active: false}} activeIDs := Map( Filter(users, func(u User) bool { return u.Active }), func(u User) int { return u.ID }, ) // [1] â type-safe, zero reflect, zero allocation overhead
Trade-offs: generics increase code readability but slightly increase compile time. The Go implementation uses GCShape monomorphisation — types with the same memory layout share one instantiation, reducing binary size compared to full C++ monomorphisation. Avoid generics for simple cases — if a plain interface satisfies the requirement, prefer it.
More Related questions...