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
Back to the full Rust cheat sheet