0
0
Rustprogramming~5 mins

Lifetime annotations in Rust

Choose your learning style9 modes available
Introduction

Lifetime annotations help Rust know how long references should be valid. They prevent bugs by making sure data lives long enough.

When you have functions that return references to data passed in as parameters.
When you want to store references in structs safely.
When multiple references interact and Rust needs help understanding their lifetimes.
When you want to avoid copying data but keep it safe.
When you want to make sure no dangling references happen in your program.
Syntax
Rust
fn function_name<'a>(param: &'a Type) -> &'a Type {
    // function body
}

Lifetime names start with an apostrophe, like 'a.

They tell Rust that the output reference lives at least as long as the input reference.

Examples
This function returns the longest string slice. The lifetime 'a means the returned reference lives as long as both inputs.
Rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}
This struct holds a reference to a string slice. The lifetime 'a ensures the reference is valid as long as the struct.
Rust
struct ImportantExcerpt<'a> {
    part: &'a str,
}
This function returns the first word in a string slice. The lifetime 'a ties the output to the input's lifetime.
Rust
fn first_word<'a>(s: &'a str) -> &'a str {
    let bytes = s.as_bytes();
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }
    &s[..]
}
Sample Program

This program finds the longest string between two inputs using lifetime annotations to ensure safety.

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

fn main() {
    let string1 = String::from("apple");
    let string2 = "banana";

    let result = longest(string1.as_str(), string2);
    println!("The longest string is: {}", result);
}
OutputSuccess
Important Notes

Lifetime annotations do not change how long data lives; they just tell Rust about it.

Rust often figures out lifetimes automatically, but sometimes you must write them explicitly.

Using lifetime annotations helps avoid crashes from invalid references.

Summary

Lifetime annotations tell Rust how long references are valid.

They use apostrophe names like 'a to connect input and output lifetimes.

They help keep programs safe by preventing dangling references.