Back to course

Lifetimes: Ensuring Reference Validity

Rust for Systems & Web3 Security

Preventing Use-After-Free

Lifetimes are a way of telling the compiler how long references should stay valid relative to each other. They use a special syntax: 'a.

rust fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } }

Most of the time, Rust elides (hides) lifetimes, but in complex systems or Web3 protocols, you'll need to specify them to ensure memory safety.