Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rust Generics: Type Parameters, Where Clauses, and Monomorphization

How generics become zero-cost code, why where clauses are not cosmetic, and how monomorphization turns one function into many.

~4 min readRust
#Rust#Generics#Syntax
3D illustration of generic type parameters branching into specialised machine-code blocks with a where-clause filter

Quick Summary

A generic item in Rust is a template the compiler fills in with concrete types. fn parse<T: FromStr>(s: &str) -> Result<T, T::Err> compiles once per type actually used at the call site, which is why generics are zero-cost: the generated code for parse::<u32> is the same machine code you would get from a hand-written u32 version. The cost is paid at compile time and in binary size instead.

The where clause is the same constraint syntax moved after the signature. It exists for readability when bounds get long, and it is required for constraints that cannot be written inline (T::Item: Display, higher-ranked bounds). Nothing about resolution changes: fn f<T>(t: T) where T: Display and fn f<T: Display>(t: T) are identical to the compiler.

Monomorphization is the part that bites in production. Every distinct T produces a separate copy of the function, so a generic called with 40 types is 40 functions in the binary. That is normally fine and desirable, but it is also the reason cargo build times climb in heavily generic crates, and why dyn dispatch exists as an escape hatch.

Basic Syntax & Signature

rust
use std::fmt::{Debug, Display}; // 1. Single bound, inline. fn print_it<T: Display>(value: T) { println!("{value}"); } // 2. Multiple bounds with `+`. fn compare<T: Display + PartialOrd>(a: T, b: T) -> T { if a > b { a } else { b } } // 3. `where` clause: same thing, readable at scale. fn render<K, V>(map: &std::collections::HashMap<K, V>) -> String where K: Display + std::hash::Hash + Eq, V: Debug, { map.iter() .map(|(k, v)| format!("{k}={v:?}")) .collect::<Vec<_>>() .join(", ") } // 4. Default type parameter and default trait method coexist. #[derive(Debug)] struct Container<T = i32> { items: Vec<T>, } // 5. Const generics: the parameter is a value, not a type. fn sum<const N: usize>(values: [u64; N]) -> u64 { values.iter().sum() } // 6. Bounds on impl blocks: only apply to some instantiations. impl<T> Container<T> { fn new() -> Self { Container { items: Vec::new() } } fn len(&self) -> usize { self.items.len() } } impl<T: Display> Container<T> { fn joined(&self) -> String { self.items.iter().map(|i| i.to_string()).collect::<Vec<_>>().join(",") } } // 7. Associated-type bound in a where clause (not expressible inline). fn first_char<I>(iter: I) -> Option<char> where I: Iterator, I::Item: AsRef<str>, { iter.filter_map(|s| s.as_ref().chars().next()).next() } // 8. Turbofish: specify the parameter the compiler cannot infer. fn main() { print_it(1u8); print_it("a str slice"); let parsed = "42".parse::<i64>().unwrap(); assert_eq!(sum([1u64, 2, 3]), 6); assert_eq!(parsed, 42); let c: Container<u8> = Container::new(); assert_eq!(c.len(), 0); }

impl Trait in argument position is sugar for an anonymous generic parameter, and in return position it is an opaque type:

rust
// Argument position: `impl Display` == a hidden generic parameter. // Each call site still monomorphizes. fn log_all(items: impl IntoIterator<Item = impl Display>) { for item in items { println!("{item}"); } } // Return position: the caller gets one concrete type, chosen by us. // No boxing, but the concrete type is unnameable outside the module. fn counters() -> impl Iterator<Item = u32> { (0..10).filter(|n| n % 2 == 0) }

The difference matters when the return type must be named in a struct field or a trait: impl Trait cannot be used there, and you fall back to Box<dyn Iterator<Item = u32>> or a named type.

Key Comparison Table

FormDispatchCode sizeCan hold mixed typesWhere usable
fn f<T: Trait>(T)Static (monomorphized)One copy per TNoFunctions, impls, traits
fn f(x: impl Trait)Static (monomorphized)One copy per concrete typeNoFunction arguments only
fn f() -> impl TraitStaticOne copyNo (one hidden type)Return position, RPIT
&dyn Trait / Box<dyn Trait>Dynamic (vtable)One copyYesAnywhere, needs indirection
where T: A + BSame as inlineSameNoAny generic item
const N: usizeMonomorphized per valueOne copy per NNoArrays, fixed buffers
Trait with associated typeStaticOne per implNoWhen each impl has one output type

Compile-time behaviour is the practical dividing line. A function taking impl Fn() -> T called with twelve closures produces twelve functions; a function taking &dyn Fn() -> T produces one and pays an indirect call. For hot loops inside a numeric kernel, static is right. For a plugin registry, a command table, or a handler map built at startup, dyn is almost always right and the vtable cost is invisible next to the I/O it wraps.

Practical Edge Cases & Deep Dives

1. Monomorphization bloat, measured

rust
// A single generic function compiled for each type it is called with. #[inline(never)] fn hash_it<T: std::hash::Hash>(value: &T) -> u64 { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); value.hash(&mut h); h.finish() } fn main() { println!("{}", hash_it(&1u8)); println!("{}", hash_it(&1u64)); println!("{}", hash_it(&"text")); println!("{}", hash_it(&(1, 2, 3))); println!("{}", hash_it(&vec![1u8, 2, 3])); }

Five call sites, five copies of hash_it. In a real crate the same effect appears at a larger scale: generic containers instantiated across a dependency graph get compiled in every downstream crate that uses them unless they are already available as pre-compiled rlib instantiations. The practical fixes are to move the generic body behind a non-generic inner function that takes &dyn (the "thin generic wrapper" pattern) and to avoid #[inline] on large generic functions.

rust
// Thin wrapper: generic outward, one non-generic body inward. fn process<T: ToString>(value: &T) -> String { process_str(&value.to_string()) } #[inline(never)] fn process_str(s: &str) -> String { s.trim().to_uppercase() }

2. Bounds the compiler cannot infer through a method call

rust
struct Wrapper<T>(T); impl<T> Wrapper<T> { // No bound here: the method exists for every T. fn get(&self) -> &T { &self.0 } } fn needs_display<T: std::fmt::Display>(w: &Wrapper<T>) -> String { // get() is callable; formatting needs the bound on T, which is present. format!("{}", w.get()) } // But this does NOT compile, because the inherent impl has no Display bound: // impl<T> Wrapper<T> { fn show(&self) -> String { format!("{}", self.0) } }

The compiler checks each item against the bounds declared in scope for that impl block. Splitting a type's methods across impl<T> and impl<T: Bound> blocks is the standard way to keep methods available to every instantiation while giving extra methods only to constrained ones — the same trick Iterator uses for collect-adjacent helpers.

3. where clauses with associated types and equality constraints

rust
use std::ops::Add; // `Output = T` constrains the associated type, which inline syntax cannot do // for a second-level bound. fn add_all<T>(items: &[T]) -> T where T: Copy + Default + Add<Output = T>, { items.iter().fold(T::default(), |acc, x| acc + *x) } fn main() { assert_eq!(add_all(&[1, 2, 3]), 6); assert_eq!(add_all(&[1.5, 2.5]), 4.0); }

Output = T is an associated type binding, not a trait bound, and it is only writable in a where clause (or as Iterator<Item = u32> inline). Without it, add_all fails with "cannot add T to T" even though T: Add is present, because Add::Output could be any type.

4. Generic methods on generic types and the trait-object boundary

rust
trait Store { fn put(&mut self, key: &str, value: &str); fn get(&self, key: &str) -> Option<&str>; } // Generic helper that works over any Store, statically dispatched. fn seed<S: Store>(store: &mut S) { store.put("a", "1"); store.put("b", "2"); } // The same logic for a heterogeneous set of stores requires dyn. fn seed_all(stores: &mut [Box<dyn Store>]) { for store in stores { store.put("a", "1"); } } // A generic METHOD cannot be called through dyn: // trait Codec { fn encode<T: serde_like::Serialize>(&self, v: &T); } // not dyn compatible

Object safety is the boundary: a trait with a generic method or a method returning Self cannot become dyn Trait. When a design needs both "one implementation per type" and "a Vec of implementations", the usual answer is to move the generic parameter into an associated type (trait Codec { type Input; fn encode(&self, v: &Self::Input); }) or to erase at the call site with a closure.

5. Const generics for fixed-size buffers

rust
// The length is part of the type, so the compiler can prove bounds. struct Frame<const N: usize> { data: [u8; N], len: usize, } impl<const N: usize> Frame<N> { fn new() -> Self { Frame { data: [0; N], len: 0 } } fn push(&mut self, byte: u8) -> Result<(), &'static str> { if self.len == N { return Err("frame full"); } self.data[self.len] = byte; self.len += 1; Ok(()) } fn as_slice(&self) -> &[u8] { &self.data[..self.len] } } fn checksum<const N: usize>(frame: &Frame<N>) -> u8 { frame.as_slice().iter().fold(0u8, |acc, b| acc.wrapping_add(*b)) } fn main() { let mut f: Frame<4> = Frame::new(); f.push(1).unwrap(); f.push(2).unwrap(); assert_eq!(checksum(&f), 3); assert_eq!(f.as_slice().len(), 2); }

Frame<4> and Frame<8> are different types and generate different code, which is the point: the array length is checked at compile time and no heap allocation is involved. The limitation is that a runtime length cannot be used — that is what Vec is for.

6. Default type parameters and the Default bound trap

rust
#[derive(Debug)] struct Cache<K, V, S = std::collections::hash_map::RandomState> { map: std::collections::HashMap<K, V, S>, } impl<K, V> Cache<K, V> where K: std::hash::Hash + Eq, { fn new() -> Self { Cache { map: std::collections::HashMap::new() } } }

Cache<String, u32> uses RandomState; Cache<String, u32, BuildHasherDefault<FxHasher>> overrides it. Defaults only apply at use sites, never inside the definition, so an impl block that wants S = RandomState must say so or stay generic over S.

Common Compilation/Runtime Mistakes

Error / symptomCauseFix
E0277: trait bound not satisfiedBound declared on the function but not on the helper it callsAdd the bound to the helper's signature, or to a where clause
E0282: type annotations neededGeneric parameter used only in the return positionTurbofish ::<T> or annotate the binding
E0207: parameter is not constrained by impl traitimpl<T> Trait for Foo where T appears nowhereMove T into a method, or add a PhantomData<T> field
E0038: trait cannot be made into an objectGeneric method or Self return in a dyn traitReplace with associated type, or add where Self: Sized
Binary size or compile time explodes after adding boundsMonomorphization across many typesThin non-generic core, dyn for heterogeneous collections
cannot add 'T' to 'T' despite T: AddAdd::Output unconstrainedT: Add<Output = T>
E0599: no method named ... foundMethod is in an impl<T: Bound> block and the bound is absentAdd the bound at the call site
Generic function cannot be used in const fn contextConst generics only support a subset of typesRestrict to usize, bool, char, integers

A final caution about impl Trait in return position: every return must produce the same concrete type, so an early return of a different iterator adapter fails. Either-style enums or Box<dyn Iterator> are the workarounds. And when a generic function is exposed from a library, remember that bounds are part of the public API: tightening T: Clone to T: Copy later is a breaking change for every caller.

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.