medium.com 5 min read Original Source

Lifetimes In Rust Finally Made Sense When I Stopped Guessing

If there is one topic that makes people close the Rust book and walk away, it is lifetimes. The syntax is strange, the error messages can be cryptic, and it is not obvious at first why the compiler is asking for any of this.

I spent more time on lifetimes than anything else when I was learning Rust. Not because they are complicated once you understand them, but because I was trying to learn the syntax before I understood the problem they solve. That was the wrong order.

This article goes problem first.

1. The Problem Lifetimes Solve

Consider this function:

&str {
if s1.len() > s2.len() {
s1
} else {
s2
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn longest(s1: &str, s2: &str) -> &str {
    if s1.len() > s2.len() {
        s1
    } else {
        s2
    }
}
fn longest(s1: &str, s2: &str) -> &str {
    if s1.len() > s2.len() {
        s1
    } else {
        s2
    }
}

The compiler rejects this. The error says something about missing lifetime specifier. Why?

Because the function returns a reference, but the compiler does not know how long that reference will be valid. The returned reference points to either s1 or s2. If the caller uses the returned reference after one of those strings is dropped, that is a use-after-free bug. The exact thing Rust exists to prevent.

The compiler is not being difficult. It genuinely cannot tell which input the output reference came from, so it cannot verify safety without more information.

Lifetimes are that information.

2. Lifetime Annotations

A lifetime annotation does not change how long anything lives. It just describes relationships between references so the compiler can verify correctness.

The syntax uses a single quote and a name:

<button data-code="fn longest(s1: &'a str, s2: &'a str) -> &'a str {
if s1.len() > s2.len() {
s1
} else {
s2
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

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

The 'a (pronounced “lifetime a”) says: the returned reference will be valid for at least as long as the shorter of s1 and s2. The compiler now has enough information to verify that any code using the result does not outlive either input.

Using it:

fn main() {
    let s1 = String::from("long string");
    let result;
{
        let s2 = String::from("xyz");
        result = longest(s1.as_str(), s2.as_str());
        println!("{}", result); // fine: result is used before s2 drops
    }
    // println!("{}", result); // ERROR: s2 is gone, result might be dangling
}
fn main() {
    let s1 = String::from("long string");
    let result;
{
        let s2 = String::from("xyz");
        result = longest(s1.as_str(), s2.as_str());
        println!("{}", result); // fine: result is used before s2 drops
    }
    // println!("{}", result); // ERROR: s2 is gone, result might be dangling
}

The compiler catches the second println! before it ever runs. No C-style dangling pointer, no segfault, no runtime crash. Just a clear compile error.

In C or C++ this compiles fine and crashes at runtime or silently corrupts memory. Java and Python avoid the problem entirely by using garbage collection, but that comes with performance and memory overhead. Rust gets safety without the garbage collector.

3. Lifetime Elision

Here is something that will confuse you if you do not know about it. Most functions with references compile without any lifetime annotations:

&str {
let bytes = s.as_bytes();
for (i, &byte) in bytes.iter().enumerate() {
if byte == b' ' {
return &s[..i];
}
}
&s[..]
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();
    for (i, &byte) in bytes.iter().enumerate() {
        if byte == b' ' {
            return &s[..i];
        }
    }
    &s[..]
}
fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();
    for (i, &byte) in bytes.iter().enumerate() {
        if byte == b' ' {
            return &s[..i];
        }
    }
    &s[..]
}

No lifetime annotations. This compiles. Why?

Because of lifetime elision rules. Rust applies a set of rules automatically when the lifetime relationships are unambiguous:

  1. Every reference parameter gets its own lifetime.
  2. If there is exactly one input reference, its lifetime is applied to all output references.
  3. If one of the parameters is &self or &mut self, the self lifetime is applied to all output references.

first_word has one input reference and one output reference. Rule 2 applies: the output lives as long as the input. The compiler fills this in for you.

You only need to write lifetime annotations when the rules cannot resolve the ambiguity on their own. Like in longest above, where there are two inputs and the compiler cannot automatically decide which one the output comes from.

4. Lifetimes in Structs

If a struct holds a reference, it needs a lifetime annotation:

<button data-code="struct Excerpt {
part: &'a str,
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago…");
let first_sentence;
{
let i = novel.find('.').unwrap_or(novel.len());
first_sentence = &novel[..i];
}

let excerpt = Excerpt { part: first_sentence };
println!("{}", excerpt.part);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

struct Excerpt<'a> {
    part: &'a str,
}
fn main() {
    let novel = String::from("Call me Ishmael. Some years ago...");
    let first_sentence;
    {
        let i = novel.find('.').unwrap_or(novel.len());
        first_sentence = &novel[..i];
    }

    let excerpt = Excerpt { part: first_sentence };
    println!("{}", excerpt.part);
}
struct Excerpt<'a> {
    part: &'a str,
}
fn main() {
    let novel = String::from("Call me Ishmael. Some years ago...");
    let first_sentence;
    {
        let i = novel.find('.').unwrap_or(novel.len());
        first_sentence = &novel[..i];
    }

    let excerpt = Excerpt { part: first_sentence };
    println!("{}", excerpt.part);
}

Excerpt<'a> says: an instance of Excerpt cannot outlive the reference it holds in part. The struct is tied to the lifetime of the string it borrows from.

This is the compiler preventing you from accidentally creating a struct that points to freed memory. In C++ you would have to track this manually. In Java there is no concept of borrowed references so the question does not arise.

Methods on structs with lifetime annotations:

<button data-code="impl Excerpt {
fn level(&self) -> i32 {
3
}
fn announce(&self, announcement: &str) -> &str {
println!("Attention: {}", announcement);
self.part // lifetime elision rule 3 applies: returns self lifetime
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

impl<'a> Excerpt<'a> {
    fn level(&self) -> i32 {
        3
    }
fn announce(&self, announcement: &str) -> &str {
        println!("Attention: {}", announcement);
        self.part // lifetime elision rule 3 applies: returns self lifetime
    }
}
impl<'a> Excerpt<'a> {
    fn level(&self) -> i32 {
        3
    }
fn announce(&self, announcement: &str) -> &str {
        println!("Attention: {}", announcement);
        self.part // lifetime elision rule 3 applies: returns self lifetime
    }
}

5. Multiple Lifetimes

Sometimes you need to express more complex relationships:

<button data-code="fn first_or_default(first: &'a str, default: &'b str) -> &'a str {
if first.is_empty() {
default // ERROR: returning 'b where 'a is expected
} else {
first
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn first_or_default<'a, 'b>(first: &'a str, default: &'b str) -> &'a str {
    if first.is_empty() {
        default // ERROR: returning 'b where 'a is expected
    } else {
        first
    }
}
fn first_or_default<'a, 'b>(first: &'a str, default: &'b str) -> &'a str {
    if first.is_empty() {
        default // ERROR: returning 'b where 'a is expected
    } else {
        first
    }
}

This does not compile. first has lifetime 'a and default has lifetime 'b. The function says it returns 'a but sometimes tries to return 'b. You need to either change the return type or constrain the lifetimes.

One approach is requiring 'b to live at least as long as 'a:

<button data-code="fn first_or_default(first: &'a str, default: &'b str) -> &'a str {
if first.is_empty() {
default
} else {
first
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn first_or_default<'a, 'b: 'a>(first: &'a str, default: &'b str) -> &'a str {
    if first.is_empty() {
        default
    } else {
        first
    }
}
fn first_or_default<'a, 'b: 'a>(first: &'a str, default: &'b str) -> &'a str {
    if first.is_empty() {
        default
    } else {
        first
    }
}

'b: 'a means 'b outlives 'a. Now returning default (which has lifetime 'b) as an 'a reference is safe because 'b is guaranteed to last at least as long as 'a.

In practice, situations requiring multiple explicit lifetimes are less common than you might expect. Most real code hits either elision rules or straightforward single-lifetime patterns.

6. The ‘static Lifetime

'static is a special lifetime that means the reference is valid for the entire duration of the program.

let s: &'static str = "I live forever";
let s: &'static str = "I live forever";

String literals are always 'static because they are embedded in the program binary. They are always there.

You will sometimes see error messages suggesting you add 'static. Be careful. The compiler sometimes suggests it when really the answer is to fix the lifetime relationships properly. Adding 'static to everything is the lifetime equivalent of making everything public in Java to avoid access control errors. It works but it is not the right answer most of the time.

7. Lifetimes with Generics and Trait Bounds

Lifetimes can be combined with generics and trait bounds:

<button data-code="use std::fmt::Display;
fn print_longest(s1: &'a str, s2: &'a str, extra: T) -> &'a str
where
T: Display,
{
println!("extra: {}", extra);
if s1.len() > s2.len() {
s1
} else {
s2
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

use std::fmt::Display;
fn print_longest<'a, T>(s1: &'a str, s2: &'a str, extra: T) -> &'a str
where
    T: Display,
{
    println!("extra: {}", extra);
    if s1.len() > s2.len() {
        s1
    } else {
        s2
    }
}
use std::fmt::Display;
fn print_longest<'a, T>(s1: &'a str, s2: &'a str, extra: T) -> &'a str
where
    T: Display,
{
    println!("extra: {}", extra);
    if s1.len() > s2.len() {
        s1
    } else {
        s2
    }
}

This combines everything: a lifetime parameter, a generic type, and a trait bound. Read the where clause in plain English: T must implement Display. That is all it says.

8. The Mental Model That Made It Click for Me

I struggled with lifetimes until I stopped thinking of them as code you write and started thinking of them as labels you attach to existing relationships.

When you write 'a on a reference, you are saying “this reference belongs to group a.” When you say a function takes &'a str and returns &'a str, you are saying “the output belongs to the same group as this input.” You are not changing when things get dropped. You are just naming the relationship so the compiler can check it.

Once you think of them as annotations describing facts about your code rather than instructions changing behavior, the syntax stops feeling arbitrary.

Summary

Lifetimes exist because Rust needs to verify that references never outlive the data they point to, and it does this at compile time. Lifetime annotations are labels describing relationships between references so the compiler can reason about safety. Elision rules handle the common cases automatically. You write explicit annotations when the relationships are ambiguous.

No garbage collector. No runtime checks. No dangling pointers. The safety guarantee comes from the type system.

What’s Next

Macros. Rust’s macro system is one of the more unique features in the language and it solves problems that would be painful to handle any other way. We will look at what macros actually are, why they exist, and how to write your own.

Happy coding and safe assembling!

Follow this series and join us in mastering Rust from scratch!