ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Rust Tutorial• 7 min read

Lifetimes: Preventing Dangling References

The 'a lifetime annotation syntax and why the borrow checker needs them

Every reference in Rust has a Lifetime—the scope for which that reference is valid. The compiler verifies lifetimes to mathematically prevent dangling references.

Lifetime Annotations ('a)

Lifetime annotations do not change how long a variable lives; they describe relationships between the lifetimes of multiple references for the compiler.

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str: Tells the compiler the returned reference will be valid as long as both input references x and y are valid.

'static: The longest possible lifetime, lasting for the entire program execution (e.g. string literals).

Explicit Lifetime Annotations in a Function
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

fn main() {
    let str1 = String::from("Systems Architecture");
    let str2 = "Rust";
    let result = longest(str1.as_str(), str2);
    println!("Longest string: {}", result);
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is the primary purpose of lifetime annotations like `'a` in Rust function signatures?