← Back to Rust Course | Chapter 12: Lifetimes | Lesson 1 of 6

Introduction to Lifetimes

A lifetime is Rust's way of tracking how long a borrowed value is actually good for, so you never use one after it's gone.

What a Lifetime Represents

A lifetime is the compiler's internal tracking of how long a particular reference remains valid, ensuring it never outlives the data it points to.

Example: What a Lifetime Represents

markup
fn main() {
    let text = String::from("valid data");
    let reference = &text;
    println!("{}", reference);
}

Most Lifetimes Are Inferred

In the vast majority of code, the compiler infers lifetime relationships automatically without you writing any lifetime syntax at all.

Example: Most Lifetimes Are Inferred

markup
fn first_word(s: &str) -> &str {
    match s.find(' ') {
        Some(i) => &s[..i],
        None => s,
    }
}

fn main() {
    let sentence = String::from("hello world");
    println!("{}", first_word(&sentence));
}

Lifetimes Prevent Dangling References

The entire purpose of lifetime tracking is to guarantee a reference can never be used after the data it points to has been freed, catching the mistake at compile time instead of causing a crash later.

Example: Lifetimes Prevent Dangling References

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

fn main() {
    let a = String::from("short");
    let b = String::from("much longer string");
    println!("{}", longest_of_two(&a, &b));
}

No Runtime Cost

Lifetime checking happens entirely during compilation. Once the code compiles successfully, no lifetime information remains in the compiled binary, and there is zero runtime overhead.

Example: No Runtime Cost

markup
fn main() {
    let value = 100;
    let borrowed = &value;
    println!("Borrowed with zero runtime cost: {}", borrowed);
}
Common Mistakes
  1. Assuming lifetimes control how long data lives -- they only describe relationships that already exist, they don't extend anything.
  2. Thinking every reference needs an explicit lifetime annotation -- most cases are inferred automatically without one.
  3. Believing lifetimes are a runtime feature -- they are purely a compile-time concept with zero runtime cost.
Chapter Summary
  • A lifetime describes how long a reference remains valid relative to the data it points to.
  • Most lifetimes are inferred automatically by the compiler and never need to be written explicitly.
  • Lifetimes exist to prevent dangling references, entirely at compile time.
  • Explicit lifetime annotations become necessary when the compiler cannot infer the relationship on its own.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.