tezvyn:

Go interface-constraint generics versus Rust trait bounds

AI-drafted, machine-checkedintermediate
WHAT IT TESTS

understanding of generics design and monomorphization.

OUTLINE

Go constrains type parameters with interfaces and may use dictionaries/shape stenciling; Rust uses trait bounds with full monomorphization for zero-cost specialization.

WHAT THIS TESTS It checks whether you understand the implementation strategies behind each language's generics and how those choices express simplicity-first versus zero-cost-abstraction values.

A GOOD ANSWER COVERS Go added generics with type parameters constrained by interfaces, where a constraint is an interface listing required methods or an allowed set of underlying types. Go's compiler does not always generate a fully specialized copy per type; it uses GC shape stenciling, producing one implementation per group of types that share a memory layout and passing a runtime dictionary for type-specific operations. This keeps binaries and compile times modest and the feature small. Rust constrains generic parameters with trait bounds and monomorphizes: for each concrete type used, the compiler emits a specialized copy, so calls are statically dispatched with no runtime indirection, fulfilling the zero-cost-abstraction goal. Rust's system also supports associated types, multiple and conditional bounds, and where-clauses.

TRADE-OFFS Rust's generics are more expressive and produce faster code but increase compile time and binary size and have a steeper learning curve. Go's generics are easier to learn and keep builds fast, but are intentionally less powerful and can carry some dictionary-based indirection.

COMMON WRONG ANSWERS Saying Go fully monomorphizes like Rust. Saying Rust generics use runtime type information. Conflating Go's constraints with Java-style type erasure (Go does not erase to Object).

LIKELY FOLLOW-UPS What is GC shape stenciling? Why can monomorphization cause code bloat? When would you prefer dynamic dispatch (interfaces or dyn Trait) over generics?

ONE CONCRETE EXAMPLE A generic Min[T constraint] in Go may compile to a single shared routine that consults a dictionary for the comparison, whereas Rust's fn min<T: Ord>(a: T, b: T) emits a distinct, inlined function for each T it is called with, so min for i32 and min for String become separate optimized code paths with no per-call type lookup.

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.