Generics & Lifetimes in Rust
From the Rust cheat sheet ยท Generics & Lifetimes ยท verified Jul 2026
Generics & Lifetimes
Generic functions, structs, and lifetime annotations.
rust
// Generic function
fn largest<T: PartialOrd>(list: &[T]) -> &T {
let mut max = &list[0];
for item in list { if item > max { max = item; } }
max
}
// Generic struct
struct Wrapper<T> { value: T }
// Lifetime annotation โ tells Rust how long references live
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}๐ก Lifetimes don't change how long data lives โ they help the compiler verify references are valid
โก Most lifetimes are inferred (elision rules) โ you only annotate when the compiler asks
๐ 'static means the reference can live for the entire program โ string literals are 'static
๐ข Rule: if a function returns a reference, it must come from an input โ not from local data
genericslifetimesbounds