Lifetimes in Rust: how long a reference lives

Learn Rust · Beginner · 12 min · After Traits in Rust: shared behaviour

How does Rust know a reference is still valid?

  1. 1Guess

    fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
        if a.len() >= b.len() { a } else { b }
    }
    
    fn main() {
        let first = String::from("lifetime");
        let second = String::from("ref");
        println!("{}", longest(&first, &second));
    }
    
    What does this program print?
  2. 2Read

    Every reference has a lifetime

    Every reference has a lifetime: the part of the program where it is valid. Most of the time the compiler infers it and you write nothing. This is called lifetime elision. The borrow checker compares lifetimes and rejects a reference that would outlive the value it points to. Without that check you would get a dangling reference.

  3. 3Code

    longest with an inner scope

    1 / 2
    fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
        if a.len() >= b.len() { a } else { b }
    }
    
    fn main() {
        let outer = String::from("long string");
        {
            let inner = String::from("short");
            let result = longest(&outer, &inner);
            println!("longest is {result}");
        }
        println!("outer is still {outer}");
    }
    

    Read the program. What will it print?

    Run it in the playground

  4. 4Read

    What the annotation says

    The annotation 'a does not make anything live longer. It describes a relation: the returned reference is valid for as long as both inputs are. A struct that holds a reference needs a lifetime parameter too: struct Excerpt<'a>. The special lifetime 'static lasts for the whole program. String literals have it.

  5. 5Code

    A struct that holds a reference

    1 / 2
    struct Excerpt<'a> {
        part: &'a str,
    }
    
    impl<'a> Excerpt<'a> {
        fn text(&self) -> &str {
            self.part
        }
    }
    
    fn main() {
        let novel = String::from("Call me Ishmael. Some years ago...");
        let first = novel.split('.').next().unwrap_or("");
        let excerpt = Excerpt { part: first };
        println!("{}", excerpt.text());
    }
    

    Read the program. What will it print?

    Run it in the playground

  6. 6Fix

    fn longest(a: &str, b: &str) -> &str {
        if a.len() >= b.len() { a } else { b }
    }
    
    fn main() {
        println!("{}", longest("lifetime", "ref"));
    }
    
    This program does not compile. What is the bug?
  7. 7Say it back

  8. 8Mission · 10 min

    Write a first_word function that returns a slice of its input, and a struct that holds a &str. Then try returning a reference to a String created inside the function and read the error.

    cargo new lifetimes
    cd lifetimes
    cargo run

Common questions

What is a lifetime in Rust?
A lifetime is the span of code where a reference is valid. Every reference has one, and the compiler usually works it out. The borrow checker uses lifetimes to make sure a reference never outlives the value it points to, which prevents dangling references. You only write lifetimes yourself when the compiler cannot tell how references relate.
Does a lifetime annotation change how long a value lives?
No. An annotation like 'a only describes how the lifetimes of references relate, so the compiler can check them. It does not extend the life of any value. In longest<'a>, it says the result is valid as long as both inputs are. If the code breaks that promise, the compiler reports an error.
What does 'static mean in Rust?
'static is a lifetime that lasts for the whole run of the program. String literals have it, because their text is stored in the program itself. A type that needs 'static holds no borrowed data that could go away. Do not add it just to silence an error: the error usually points to a real ownership problem.

Sources

Measured with rustc 1.100.1 (play.rust-lang.org, stable, edition 2024) on 2026-12-03

Published Dec 3, 2026 · Updated Dec 3, 2026

Never miss new offers and news

New tools, credits, and AI news are added regularly. Pick how you want to hear about them.

Telegram channel

Join @aifree_dev and get new free AI offers and news right in your Telegram feed.

Browser notifications

Turn on push notifications and get an alert on this device whenever something new is posted. No account needed.

Email newsletter

A weekly digest of new, changed and expiring free AI offers. Double opt-in, one-click unsubscribe. See the latest issue.

Unsubscribe anytime. Privacy

Frequently asked questions

What is aifree.dev?

aifree.dev helps everyone access AI through a curated directory of free AI tools, API credits, free tiers, and startup programs for coding, image, voice, video, and students - verified regularly.

How are offers presented?

Each offer includes its access details, free models when available, and expiration information when provided. Limited-time deals stay visible so they are easy to compare.

Do education and startup programs need verification?

Yes. Providers usually ask students to verify their status with a school email, student ID, or a program like the GitHub Student Pack, and ask startups to verify company details such as age, funding, or website. Check each offer’s claim page for the exact requirements.

What kinds of free AI offers are listed?

Free tiers and free trials from AI providers, free API credits, startup and student programs, and free tools for coding, image generation, voice, and video.

How can I suggest a tool or report a broken link?

Use the submit form: paste the offer page URL and a short note. A person checks every submission before anything is listed. Broken links and changed terms go through the same form.

Know a good one?

Tell us about an AI tool worth knowing. Found a broken link? We want to hear that too.

Submit an offer