🦀 Rust Intermediate

What are lifetimes in structs and function signatures in Rust?

Answer

Explicit lifetime annotations are required in two main places. In function signatures: when a function takes multiple reference parameters and returns a reference, the compiler needs to know which input lifetime the output reference is tied to. Example: fn first_word<'a>(s: &'a str) -> &'a str — this tells the compiler the returned reference lives at least as long as the input s. In structs: if a struct holds a reference, it needs a lifetime parameter to ensure the struct cannot outlive the data it references. Example: struct Excerpt<'a> { text: &'a str }. This prevents creating an Excerpt that holds a dangling reference to a String that has been dropped. Lifetimes are never at runtime — they are purely a compile-time annotation for the borrow checker.