Skip to content

Rust Lifetimes — Lifetime Annotations, Elision Rules, and Struct Lifetime Parameters

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Rust Lifetimes. We cover key concepts, practical examples, and best practices to help you master this topic.

Rust lifetimes ensure references are always valid with annotations like 'a, elision rules for common patterns, and lifetime parameters on structs.

What You'll Learn

  • Lifetime annotations
  • Lifetime elision rules
  • Struct lifetime parameters
  • Static lifetime

Why It Matters

Lifetimes prevent dangling references at compile time. DodaZIP uses lifetimes for zero-copy Parsing. Firefox uses lifetimes for DOM node references.

Real-World Use

Zero-copy parsing, string processing, data structure references, cache implementations.

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

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

fn main() {
    let string1 = String::from("long string is long");
    let result;
    {
        let string2 = String::from("xyz");
        result = longest(string1.as_str(), string2.as_str());
        println!("Longest: {}", result);
    }

    let novel = String::from("Call me Ishmael. Some years ago...");
    let excerpt = Excerpt {
        part: &novel[..novel.find('.').unwrap_or(novel.len())],
    };
    println!("Excerpt: {}", excerpt.part);

    // Static lifetime
    let s: &'static str = "I live forever";
    println!("{}", s);
}

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro