Generics
Generics parameterize types and functions so one implementation works for many concrete types while staying type-safe and zero-cost.
Busca en todas las páginas de la documentación
Generics parameterize types and functions so one implementation works for many concrete types while staying type-safe and zero-cost.
fn largest<T: PartialOrd>(list: &[T]) -> &T {
list.iter().max_by(|a, b| a.partial_cmp(b).unwrap()).unwrap()
}
struct Wrapper<T>(T);
impl<T: std::fmt::Debug> Wrapper<T> {
fn debug(&self) { println!("{:?}", self.0); }
}When to reach for this: Containers, algorithms, and APIs reusable across types without dyn overhead.
struct Page<T> { items: Vec<T>, page: u32 }
impl<T> Page<T> {
fn new(items: Vec<T>) -> Self {
Self { items, page: 1 }
}
fn len(&self) -> usize { self.items.len() }
}
fn main() {
let p = Page::new(vec![1, 2, 3]);
println!("{}", p.len());
}What this demonstrates:
Page<T>TTdynFunctions, structs, enums, impls, and traits accept type params <T>, const params <const N: usize>, and lifetimes 'a.
let v = Vec::<i32>::new();
let s = "42".parse::<u32>().unwrap();struct Buffer<const N: usize> { data: [u8; N] }T inflate binary size. Fix: Dynamic dispatch dyn Trait or type erasure at boundary.T has no methods. Fix: Add T: Trait bounds.::<N>. Fix: Annotate const param.where clause formatting.| Alternative | Use When | Don't Use When |
|---|---|---|
dyn Trait | Runtime heterogeneity | Hot path needs inline |
| Macros | Generate per-type code | Generics expressible |
enum of types | Closed set of variants | Open-ended T |
| Type alias | Simplify long generics | Only one instantiation used |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026