🦀 Rust
Intermediate
What are generics in Rust and how do where clauses work?
Answer
Generics let you write code that works over many types while maintaining type safety. A generic function: fn largest<T: PartialOrd>(list: &[T]) -> &T. The T: PartialOrd is a trait bound — it constrains which types are valid. Where clauses move complex bounds out of the function signature into a more readable position: fn foo<T, U>(t: T, u: U) where T: Display + Clone, U: Debug. Rust implements generics through monomorphization: the compiler generates a separate concrete function for each unique type argument at compile time, resulting in zero-cost abstractions with no runtime overhead. The trade-off is larger binary size compared to dynamic dispatch. Generics work with functions, structs, enums, and impl blocks.