0
0
Rustprogramming~5 mins

Lifetime elision rules in Rust

Choose your learning style9 modes available
Introduction

Lifetime elision rules help Rust understand how long references live without you writing extra code. This makes your code simpler and easier to read.

When writing functions that take references as parameters and return references.
When you want Rust to automatically figure out lifetimes instead of specifying them manually.
When defining methods on structs that use references.
When you want to avoid cluttering your code with lifetime annotations but still keep it safe.
Syntax
Rust
fn function_name(&self, param: &Type) -> &Type {
    // function body
}

Rust applies three main lifetime elision rules automatically.

You only need to write lifetime annotations if Rust cannot figure them out from these rules.

Examples
Rust applies elision rules here so you don't need to write lifetimes explicitly.
Rust
fn first_word(s: &str) -> &str {
    // returns a slice of the input string
}
Here, explicit lifetimes are needed because Rust cannot guess if the output lifetime matches one of the inputs.
Rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}
Methods with &self have lifetimes elided automatically for &self and return types.
Rust
impl<'a> ImportantExcerpt<'a> {
    fn level(&self) -> i32 {
        3
    }
}
Sample Program

This program shows a struct holding a reference with a lifetime. The method uses lifetime elision rules so we don't write lifetimes on &self, the parameter, or the return type.

Rust
struct ImportantExcerpt<'a> {
    part: &'a str,
}

impl<'a> ImportantExcerpt<'a> {
    // Method with elided lifetimes
    fn announce_and_return_part(&self, announcement: &str) -> &str {
        println!("Announcement: {}", announcement);
        self.part
    }
}

fn main() {
    let text = String::from("Rust is awesome!");
    let excerpt = ImportantExcerpt { part: &text[0..4] };

    let announcement = "Here is an important part:";
    let result = excerpt.announce_and_return_part(announcement);

    println!("Returned part: {}", result);
}
OutputSuccess
Important Notes

Time complexity: Lifetime elision does not affect runtime; it is a compile-time feature.

Space complexity: No impact on memory usage.

Common mistake: Expecting Rust to always guess lifetimes; sometimes you must write them explicitly.

When to use: Use elision to keep code clean, but add explicit lifetimes when Rust cannot infer them.

Summary

Lifetime elision rules let Rust fill in lifetimes automatically in common cases.

There are three main rules that Rust follows to guess lifetimes.

Use explicit lifetimes only when Rust cannot figure them out on its own.