Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 11 · Lifetimes & smart pointers

    11.1Lifetimes

    What 'a and 'static really mean, why a function that returns a reference sometimes needs one, the three rules that let you leave them out, and when to hold owned data instead.

    About 35 minutesIntermediate

    On this page
    1. Concept map
    2. Reachability vs. scopes
    3. Why longest needs 'a
    4. What the caller sees
    5. Tie the result only to what it borrows from
    6. When you can leave lifetimes out
    7. Structs that hold references
    8. 'static: two meanings
    9. Which one should I use?
    10. Under the hood
    11. Common pitfalls
    12. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    How long a value stays aliveUntil nothing refers to it; the garbage collector decidesUntil nothing refers to it; the garbage collector decidesUntil its owner's scope ends. A reference can't extend it.
    A function that returns one of its argumentsfunction longest(a: string, b: string): stringstatic string Longest(string a, string b)fn longest<'a>(a: &'a str, b: &'a str) -> &'a str
    'aNothing similarNothing you can name; ref returns follow fixed ref-safety rules (scoped opts a parameter out)A name that links a borrow to the value it borrows from; the compiler works out how long it lasts
    An object that keeps a view into anotherAny field can refer to any objectAny field; a ref struct can hold a Span<T> but can't outlive itstruct Highlight<'a> { text: &'a str }: can't outlive the text
    'staticNo equivalentNo equivalent (static is a type member)&'static T: valid until the program ends. T: 'static: holds no borrow that can expire

    Lifetimes have a reputation as the hardest part of Rust, mostly because of how they look: <'a>, &'a str, 'static. The idea underneath is small. In TypeScriptC#, the garbage collector keeps an object alive for as long as anything refers to it. Rust has no collector: a value lives until its owner’s scope ends, full stop, and the compiler checks that no reference is used after that. A lifetime is the compiler’s name for “the stretch of code where this borrow is valid”, and the compiler works each one out for itself. You’ll rarely write one. When a function hands back a reference, you sometimes have to say which input it came from, and 'a is how you say it: a label that ties the result to an input, not a duration you choose.

    Reachability vs. scopes

    Here’s a function that picks the captain from a team, and a caller that keeps the captain after the team is gone. In TypeScriptC#, that’s fine: the list may be collected, but the garbage collector keeps whatever captain refers to alive. In Rust, it doesn’t compile.

    TypeScript
    captain.ts
    function captainOf(team: string[]): string {
      return team[0]!;
    }
    
    let captain: string;
    {
      const team = ["Ada", "Grace"];
      captain = captainOf(team);
    } // `team` is out of scope, but the GC keeps what `captain` refers to alive
    console.log(captain);
    C#
    Captain.cs
    string captain;
    {
        var team = new List<string> { "Ada", "Grace" };
        captain = CaptainOf(team);
    } // `team` is out of scope, but the GC keeps what `captain` refers to alive
    Console.WriteLine(captain);
    
    static string CaptainOf(List<string> team) => team[0];
    Rust
    fn captain_of(team: &[String]) -> &str {
        &team[0]
    }
    
    fn main() {
        let captain;
        {
            let team = vec![String::from("Ada"), String::from("Grace")];
            captain = captain_of(&team);
        } // `team` is dropped here, and both names with it
        println!("{captain}");
    }

    Output of the TypeScriptC# version

    Ada

    Rust doesn't compile this: error E0597

    error[E0597]: `team` does not live long enough
      --> captain.rs:9:30
       |
     8 |         let team = vec![String::from("Ada"), String::from("Grace")];
       |             ---- binding `team` declared here
     9 |         captain = captain_of(&team);
       |                              ^^^^^ borrowed value does not live long enough
    10 |     } // `team` is dropped here, and both names with it
       |     - `team` dropped here while still borrowed
    11 |     println!("{captain}");
       |                ------- borrow later used here

    team owns the vector and both Strings in it, so all of them are freed at the inner closing brace. captain is a &str pointing into the first name’s heap buffer. Using it on the last line would read freed memory, so the compiler rejects the borrow. Here’s the same code as a timeline, with one column per value or borrow and a bar for the lines where each is alive:

    captain outlives team
    captain outlives team. Each column is a value or a borrow; a mark means it's alive on that line.
    LineCodeteamownercaptainshared borrow (&)What happens
    1let captain;
    2{
    3 let team = vec![String::from("Ada"), String::from("Grace")];ownsteam starts
    4 captain = captain_of(&team);team alive&captain startserrorE0597: the borrow of team must last until line 6
    5} // `team` is dropped here, and both names with itteam endscaptain aliveteam is dropped: the vector and both names are freed
    6println!("{captain}");captain endsLast use of captain

    A timeline of the main function above. team owns the vector from line 3 until the closing brace on line 5, where it's dropped. captain borrows from team on line 4 and is used on line 6, so the borrow must last from line 4 to line 6. Lines 5 and 6 are past the end of team, so the compiler rejects the borrow on line 4 with E0597.

    Two things to notice. First, the compiler never made team live longer to fix the problem. In Rust, a reference can’t keep anything alive; only the owner decides that. Second, the compiler knew that captain borrows from team without reading the body of captain_of. It worked that out from the signature alone: one reference goes in, one comes out, so the result must borrow from the input. When the signature doesn’t make that obvious, you have to spell it out. That’s where 'a comes in.

    The fix is to keep using captain only while team is alive, or to make captain an owned value of its own: captain_of(&team).to_string() copies the name into a new String that outlives the team.

    Why longest needs 'a

    Here’s a function with two text parameters that returns the longer one. TypeScriptC# accepts it as written. Rust doesn’t:

    TypeScript
    longest.ts
    function longest(a: string, b: string): string {
      return a.length >= b.length ? a : b;
    }
    
    console.log(longest("Grace", "Ada"));
    C#
    Longest.cs
    Console.WriteLine(Longest("Grace", "Ada"));
    
    static string Longest(string a, string b) => a.Length >= b.Length ? a : b;
    Rust
    fn longest(a: &str, b: &str) -> &str {
        if a.len() >= b.len() { a } else { b }
    }
    
    fn main() {
        println!("{}", longest("Grace", "Ada"));
    }

    Output of the TypeScriptC# version

    Grace

    Rust doesn't compile this: error E0106

    error[E0106]: missing lifetime specifier
     --> main.rs:1:33
      |
    1 | fn longest(a: &str, b: &str) -> &str {
      |               ----     ----     ^ expected named lifetime parameter
      |
      = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `a` or `b`
    help: consider introducing a named lifetime parameter
      |
    1 | fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
      |           ++++     ++          ++          ++

    The error is E0106, “missing lifetime specifier”. The compiler has the same question as before: the result is a reference, so which input does it borrow from? With one reference parameter it could guess. With two, it won’t, because the answer changes what callers are allowed to do. Here, the result can be either a or b, so you say so:

    fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
        if a.len() >= b.len() { a } else { b }
    }
    
    fn main() {
        println!("{}", longest("Grace", "Ada"));
    }

    Output

    Grace

    Read it piece by piece:

    • <'a> declares a lifetime parameter, the way <T> declares a type parameter. The apostrophe marks it as a lifetime; a is just a name. ('a', with a closing quote, would be a char.)
    • a: &'a str and b: &'a str say “both inputs are borrowed for at least 'a”.
    • -> &'a str says “the result is valid for 'a, and no longer”.

    Put together: the result may borrow from a or b, so it’s only valid while both are. That’s the whole meaning.

    Mental model shiftA lifetime is a constraint, not a duration you choose

    'a doesn’t set how long anything lives, and writing it never changes when a value is dropped. Owners decide that, at the end of their scope. A lifetime annotation is a relationship written in a signature: “this output borrows from these inputs”. At each call, the compiler works out the actual stretch of code for 'a (the lines where the result is used) and checks that every argument tied to it is alive on all of them. If you get the relationship wrong, the compiler rejects the function or its callers. It never produces a dangling reference.

    C# has a hidden version of the same rule, for ref returns. A method that returns a ref to one of its ref parameters is fine, and the compiler assumes the result might point at any of them, so a caller can only use it while every argument is still in scope:

    Larger.cs
    int first = 5;
    int second = 3;
    ref int larger = ref Larger(ref first, ref second);
    larger = 0; // writes to `first`
    Console.WriteLine($"{first} {second}");
    
    static ref int Larger(ref int a, ref int b) => ref (a >= b ? ref a : ref b);

    Output

    0 3

    That’s exactly what 'a on both parameters says. The difference is that C# never lets you name it: its ref-safety rules use a few fixed scopes, and the main annotation you get is scoped, which marks a parameter the result can’t come from. Rust lets you write any relationship, and applies it to every reference, not just ref locals and spans.

    What the caller sees

    The relationship matters at the call site. Here the result is used after the shorter-lived input is gone:

    fn main() {
        let first = String::from("Grace");
        let winner;
        {
            let second = String::from("Ada");
            winner = longest(&first, &second);
        } // `second` is dropped here
        println!("{winner}");
    }

    Rust doesn't compile this: error E0597

    error[E0597]: `second` does not live long enough
      --> main.rs:6:34
       |
     5 |         let second = String::from("Ada");
       |             ------ binding `second` declared here
     6 |         winner = longest(&first, &second);
       |                                  ^^^^^^^ borrowed value does not live long enough
     7 |     } // `second` is dropped here
       |     - `second` dropped here while still borrowed
     8 |     println!("{winner}");
       |                ------ borrow later used here
    The result can't outlive the shorter input
    The result can't outlive the shorter input. Each column is a value or a borrow; a mark means it's alive on that line.
    LineCodefirstownersecondownerwinner ('a)shared borrow (&)What happens
    1let first = String::from("Grace");ownsfirst starts
    2let winner;first alive
    3{first alive
    4 let second = String::from("Ada");first aliveownssecond starts
    5 winner = longest(&first, &second);first alivesecond alive&winner ('a) startserrorE0597: 'a must last until line 7, but second ends on line 6
    6} // `second` is dropped herefirst alivesecond endswinner ('a) alivesecond is dropped
    7println!("{winner}");first endswinner ('a) endsLast use of winner

    A timeline of the body of main above. first owns Grace from line 1 to line 7. second owns Ada only from line 4 to the closing brace on line 6. winner borrows from both on line 5 and is used on line 7, so 'a must cover lines 5 to 7. second is dropped on line 6, inside that range, so the compiler rejects the borrow of second on line 5 with E0597.

    At run time this would have been safe: "Grace" is longer, so winner would point at first, which is still alive. The compiler rejects it anyway, because it checks the signature, not the values. The signature says the result might be b, so second must live as long as winner is used. Move the println! inside the block and every borrow ends while both strings are alive:

    fn main() {
        let first = String::from("Grace");
        {
            let second = String::from("Ada");
            let winner = longest(&first, &second);
            println!("{winner}");
        }
    }

    Output

    Grace

    Tie the result only to what it borrows from

    Give a parameter the result never borrows from a lifetime of its own, or no name at all. Here prefix is only read, so it doesn’t need 'a, and the caller can drop it early:

    fn strip<'a>(text: &'a str, prefix: &str) -> &'a str {
        text.strip_prefix(prefix).unwrap_or(text)
    }
    
    fn main() {
        let line = String::from("> quoted reply");
        let body;
        {
            let prefix = String::from("> ");
            body = strip(&line, &prefix);
        } // `prefix` is dropped here, and that's fine
        println!("{body}");
    }

    Output

    quoted reply

    If you’d written prefix: &'a str too, this caller would fail with E0597, just like longest. The more precisely a signature states where its result comes from, the more callers it accepts.

    When you can leave lifetimes out

    Every reference has a lifetime, but most signatures don’t show them. The compiler fills them in with three elision rules, applied in order:

    1. Each reference parameter gets its own lifetime.
    2. If there’s exactly one input lifetime, the output gets it.
    3. If there’s a &self or &mut self, the output gets the lifetime of self.

    If the output still has a reference with no lifetime after that, you get E0106 and write it yourself.

    You writeThe compiler readsRules
    fn count(text: &str) -> usizefn count<'a>(text: &'a str) -> usize1 (no reference out, so nothing more to do)
    fn first_word(text: &str) -> &strfn first_word<'a>(text: &'a str) -> &'a str1, 2
    fn find(&self, prefix: &str) -> Option<&str>fn find<'a, 'b>(&'a self, prefix: &'b str) -> Option<&'a str>1, 3
    fn longest(a: &str, b: &str) -> &strNothing fits: two inputs and no selfE0106

    Here are the second and third rows as working code:

    fn first_word(text: &str) -> &str {
        text.split_whitespace().next().unwrap_or("")
    }
    
    struct Library {
        books: Vec<String>,
    }
    
    impl Library {
        // Rule 3: the result borrows from `self`, not from `prefix`
        fn find(&self, prefix: &str) -> Option<&str> {
            self.books
                .iter()
                .find(|book| book.starts_with(prefix))
                .map(|book| book.as_str())
        }
    }
    
    fn main() {
        println!("{}", first_word("hello world"));
        let library = Library {
            books: vec![String::from("Dune"), String::from("Emma")],
        };
        println!("{:?}", library.find("Em"));
    }

    Output

    hello
    Some("Emma")

    Rule 3 is a guess that’s right for almost every method: a method that returns a reference usually returns part of self. When it isn’t right, say a method that returns part of a parameter, you write the lifetimes out, as in strip.

    Structs that hold references

    A struct can hold a reference too. Here’s a Highlight that points at the first sentence of a book. In TypeScriptC#, its field is an ordinary reference to a string. In Rust, it’s a borrow, so the struct needs a lifetime parameter: Highlight<'a> means “a highlight that borrows text for 'a”.

    TypeScript
    highlight.ts
    type Highlight = { text: string };
    
    function firstSentence(book: string): Highlight {
      const end = book.indexOf(".");
      return { text: end === -1 ? book : book.slice(0, end + 1) };
    }
    
    const book = "Call me Ishmael. Some years ago, never mind how long.";
    const highlight = firstSentence(book);
    console.log(highlight.text);
    C#
    Highlight.cs
    var book = "Call me Ishmael. Some years ago, never mind how long.";
    var highlight = FirstSentence(book);
    Console.WriteLine(highlight.Text);
    
    static Highlight FirstSentence(string book)
    {
        var end = book.IndexOf('.');
        return new Highlight(end == -1 ? book : book[..(end + 1)]);
    }
    
    record Highlight(string Text);
    Rust
    struct Highlight<'a> {
        text: &'a str,
    }
    
    fn first_sentence(book: &str) -> Highlight<'_> {
        let end = book.find('.').map_or(book.len(), |i| i + 1);
        Highlight { text: &book[..end] }
    }
    
    fn main() {
        let book = String::from("Call me Ishmael. Some years ago, never mind how long.");
        let highlight = first_sentence(&book);
        println!("{}", highlight.text);
    }

    Output

    Call me Ishmael.

    Highlight<'_> in the return type means “a Highlight with the elided lifetime”, which rule 2 ties to book. The Rust version copies no text: highlight.text points into book’s buffer. The C# version copies the sentence into a new string. The C# type that shares Rust’s restrictions is a ref struct holding a ReadOnlySpan<char>: it also copies nothing, and the compiler also stops it from outliving the text (it can’t be stored in a class field, for example).

    The price is that a Highlight can never outlive the String it borrows from. Free the book while the highlight still points into it and the compiler refuses:

    let book = String::from("Call me Ishmael. Some years ago, never mind how long.");
    let highlight = first_sentence(&book);
    drop(book); // free the book now
    println!("{}", highlight.text);

    Rust doesn't compile this: error E0505

    error[E0505]: cannot move out of `book` because it is borrowed
      --> main.rs:3:6
       |
     1 | let book = String::from("Call me Ishmael. Some years ago, never mind how long.");
       |     ---- binding `book` declared here
     2 | let highlight = first_sentence(&book);
       |                                ----- borrow of `book` occurs here
     3 | drop(book); // free the book now
       |      ^^^^ move out of `book` occurs here
     4 | println!("{}", highlight.text);
       |                -------------- borrow later used here
       |
    help: consider cloning the value if the performance cost is acceptable
       |
     2 | let highlight = first_sentence(&book.clone());
       |                                     ++++++++
    A struct can't outlive what it borrows
    A struct can't outlive what it borrows. Each column is a value or a borrow; a mark means it's alive on that line.
    LineCodebookownerbookmoved outhighlightshared borrow (&)What happens
    1let book = String::from("Call me Ishmael. Some years ago, never mind how long.");ownsbook starts
    2let highlight = first_sentence(&book);book ends&highlight starts
    3drop(book); // free the book nowmovedbook startshighlight aliveerrorE0505: book can't move into drop while highlight borrows it
    4println!("{}", highlight.text);book endshighlight endsLast use of highlight

    A timeline of the four lines above. book owns the text on lines 1 and 2, and on line 3 it's moved into drop, which frees it. highlight borrows from book from line 2 until its last use on line 4. Line 3 tries to move book while highlight still borrows it, so the compiler rejects it with E0505.

    And without the <'a>, the struct itself doesn’t compile. A reference field needs a named lifetime, so that each Highlight can be tied to whatever it borrows from:

    struct Highlight {
        text: &str,
    }

    Rust doesn't compile this: error E0106

    error[E0106]: missing lifetime specifier
     --> main.rs:2:11
      |
    2 |     text: &str,
      |           ^ expected named lifetime parameter
      |
    help: consider introducing a named lifetime parameter
      |
    1 ~ struct Highlight<'a> {
    2 ~     text: &'a str,
      |

    Idiomatic RustPrefer owned fields

    A struct with a lifetime parameter is a view: great for short-lived helpers like a parser walking over a buffer, awkward for anything you store, return from deep inside your program, or send to another thread. The lifetime also spreads: any struct that holds a Highlight<'a> needs its own <'a>. When in doubt, own the data: struct Highlight { text: String } has no lifetime, and costs one copy of the sentence.

    'static: two meanings

    'static is the one lifetime with a built-in name. You’ll see it in two places, and they mean different things.

    &'static T: a borrow that’s valid until the program ends. String literals are the common case: their text is stored in the compiled program, so a &'static str can be used anywhere, for as long as you like. Slices covers why. static items (global values) are the other source.

    static APP_NAME: &str = "binshelf";
    
    fn status_label(code: u16) -> &'static str {
        match code {
            200 => "ok",
            404 => "not found",
            _ => "unknown",
        }
    }
    
    fn main() {
        println!("{APP_NAME}: {}", status_label(404));
    }

    Output

    binshelf: not found

    status_label has no reference parameters, so no elision rule applies; the result is always a literal, and 'static says so.

    T: 'static: a type that holds no borrow that could expire. This is a bound on a type, not a promise that a value lives forever. Every owned type meets it: String, Vec<i32>, u64, your own structs without reference fields. A &'a str with a shorter 'a doesn’t. You’ll meet it on std::thread::spawn, whose closure must be 'static because the new thread can run for longer than the function that started it:

    use std::thread;
    
    fn main() {
        let name = String::from("Ada");
        // `move` gives the String to the closure, which now owns it: 'static is satisfied
        let handle = thread::spawn(move || format!("Hello, {name}!"));
        println!("{}", handle.join().expect("the thread panicked"));
    }

    Output

    Hello, Ada!

    name meets the bound, and it’s still an ordinary String: it’s freed when the thread’s closure finishes, not at the end of the program. What fails is lending the thread a borrow of a local:

    use std::thread;
    
    fn main() {
        let name = String::from("Ada");
        let greeting = &name;
        let handle = thread::spawn(move || format!("Hello, {greeting}!"));
        println!("{}", handle.join().expect("the thread panicked"));
    }

    Rust doesn't compile this: error E0597

    error[E0597]: `name` does not live long enough
     --> main.rs:5:20
      |
    4 |     let name = String::from("Ada");
      |         ---- binding `name` declared here
    5 |     let greeting = &name;
      |                    ^^^^^ borrowed value does not live long enough
    6 |     let handle = thread::spawn(move || format!("Hello, {greeting}!"));
      |                  ---------------------------------------------------- argument requires that `name` is borrowed for `'static`
    7 |     println!("{}", handle.join().expect("the thread panicked"));
    8 | }
      | - `name` dropped here while still borrowed
      |
    note: requirement that the value outlives `'static` introduced here

    The compiler’s message names the requirement: the argument requires that name is borrowed for 'static.

    You seeIt meansExample
    &'static strA borrow valid until the program endsA string literal; a static item
    T: 'staticT holds no borrow that can expire; it may still be freed earlyString, Vec<T>, a struct with owned fields
    static NAME: TA global item, not a lifetimestatic APP_NAME: &str = "binshelf";

    Reading Rust’s symbols has the full list of things called “static”, including TypeScript's static class membersC#'s static members.

    Which one should I use?

    WhatWhenWhyHow
    No annotation (elision)A function with one reference parameter, or a method with &self. The default.The compiler fills in the obvious relationship.fn first_word(text: &str) -> &str
    <'a> on a functionIt returns a reference and has two or more reference parameters, and no &self.Tells the compiler and the reader which inputs the result borrows from, so callers keep them alive.fn longest<'a>(a: &'a str, b: &'a str) -> &'a str; leave inputs the result doesn’t borrow from unnamed.
    struct Name<'a>A short-lived view into data someone else owns: a parser, an iterator, a highlight.No copying.struct Highlight<'a> { text: &'a str }, returned as Highlight<'_>.
    Owned fieldsThe struct is stored, returned up the call stack, or sent to another thread.No lifetime to carry around; the struct can outlive its source.struct Highlight { text: String }
    &'static strThe result is fixed text written in the code.No allocation, valid everywhere.fn status_label(code: u16) -> &'static str
    T: 'staticAn API keeps a value with no end in sight: a thread, a global registry.Guarantees no borrow inside the value can expire.Pass owned data: thread::spawn(move || ...).

    Rule of thumb: don’t write lifetimes until the compiler asks. When it does, it’s because a function returns a reference and the signature doesn’t say which input it comes from: name that input with 'a, and only that input. For structs, start with owned fields and add <'a> only for short-lived views.

    Do I need to write a lifetime?
    1. Does the function return a reference to something it creates inside?

      Yes

      No lifetime can help: return an owned valueA local is dropped when the function returns (E0515). Return String, Vec<T> or your struct instead.

      No
    2. Does a struct need to hold a reference?

      Yes

      Prefer an owned field. If it must borrow, write struct Name<'a>Owned fields (String, Vec<T>) let the struct outlive its source. Borrow only in short-lived views, such as a parser over a buffer.

      No
    3. Is the result a fixed string written in the code?

      Yes

      Return &'static strLiterals are valid until the program ends.

      No
    4. Does the function return a reference, take two or more reference parameters, and have no &self?

      Yes

      Write <'a> on the result and on the parameters it borrows fromThe compiler asks with E0106. Leave the other parameters unnamed.

      No
    5. Otherwise: Write nothing: elision covers one reference parameter and methods with &self. If the compiler asks anyway, read its suggestion; don't reach for 'static.

    Under the hood

    Lifetimes exist only while the compiler checks your code. They’re erased before code generation: on a 64-bit target, a &'a str and a &'static str are the same 16 bytes (a pointer and a length), and a Highlight<'a> is just its reference:

    println!("&str: {} bytes", size_of::<&str>());
    println!("&'static str: {} bytes", size_of::<&'static str>());
    println!("Highlight: {} bytes", size_of::<Highlight<'_>>());

    Output

    &str: 16 bytes
    &'static str: 16 bytes
    Highlight: 16 bytes

    Nothing is counted or tracked when the program runs. The checking works like this:

    • A lifetime parameter is a generic parameter. longest<'a> is one function that works for any 'a, the way Vec<T> works for any T. At each call, the compiler picks 'a for that call: the smallest stretch of code that covers every use of the result.
    • Every argument tied to 'a must be alive for all of it. In the timeline of the longest caller, 'a had to cover lines 5 to 7, and second ended on line 6. That’s the whole check.
    • Longer lifetimes fit where shorter ones are expected. 'static outlives every other lifetime, so a literal can go anywhere a &'a str is expected: longest("Grace", &name) compiles, and 'a is just the part where name is alive.
    • Borrows end at their last use, not at the closing brace, as in References. That’s why moving the println! inside the block fixed the longest caller.

    You can also write “'a outlives 'b” yourself, as 'a: 'b, and see lifetimes in trait objects (Box<dyn Trait + 'a>). Both are rare in application code; the compiler’s messages tell you when you need them.

    Common pitfalls

    Common pitfallA lifetime can't make a value live longer

    Annotations describe borrows; they don’t extend anything. A function can’t return a reference to its own local, whatever lifetime you write on it:

    fn make_greeting<'a>(name: &str) -> &'a str {
        let greeting = format!("Hello, {name}!");
        &greeting
    }

    Rust doesn't compile this: error E0515

    error[E0515]: cannot return reference to local variable `greeting`
     --> main.rs:3:5
      |
    3 |     &greeting
      |     ^^^^^^^^^ returns a reference to data owned by the current function

    greeting is dropped when the function returns. Return the String itself: fn make_greeting(name: &str) -> String.

    Common pitfallAdding 'static moves the error to the caller

    When the compiler complains about a lifetime, it’s tempting to write 'static everywhere. That compiles the function, then rejects every caller that passes anything but a literal:

    fn first_word(text: &'static str) -> &'static str {
        text.split_whitespace().next().unwrap_or("")
    }
    
    fn main() {
        let sentence = String::from("hello world");
        println!("{}", first_word(&sentence));
    }

    Rust doesn't compile this: error E0597

    error[E0597]: `sentence` does not live long enough
     --> main.rs:7:31
      |
    6 |     let sentence = String::from("hello world");
      |         -------- binding `sentence` declared here
    7 |     println!("{}", first_word(&sentence));
      |                    -----------^^^^^^^^^-
      |                    |          |
      |                    |          borrowed value does not live long enough
      |                    argument requires that `sentence` is borrowed for `'static`
    8 | }
      | - `sentence` dropped here while still borrowed

    Remove the 'statics and let elision tie the result to text. Reach for 'static only when the data really is fixed in the program, or when an API like thread::spawn needs owned data, and then pass owned data.

    Common pitfallTemporaries are dropped at the end of the statement

    A value that isn’t stored in a variable is a temporary, and it’s dropped at the semicolon. Borrowing from one and keeping the borrow fails:

    let name: &str = String::from("Ada").as_str();
    println!("{name}");

    Rust doesn't compile this: error E0716

    error[E0716]: temporary value dropped while borrowed
     --> main.rs:1:18
      |
    1 | let name: &str = String::from("Ada").as_str();
      |                  ^^^^^^^^^^^^^^^^^^^         - temporary value is freed at the end of this statement
      |                  |
      |                  creates a temporary value which is freed while still in use
    2 | println!("{name}");
      |            ---- borrow later used here
      |
    help: consider using a `let` binding to create a longer lived value
      |
    1 ~ let binding = String::from("Ada");
    2 ~ let name: &str = binding.as_str();
      |

    The String is gone after line 1, so name would dangle. Keep the owner in a variable first: let owned = String::from("Ada"); let name = owned.as_str();.

    Common pitfallDon't hide a struct's lifetime

    fn first_sentence(book: &str) -> Highlight compiles, but the compiler warns (mismatched_lifetime_syntaxes), because the return type borrows from book and nothing in it shows that. Write Highlight<'_>: the '_ tells readers “this borrows from an input”, and it’s what the compiler suggests.

    Try it yourself

    Exercise: port this to Rust

    Port this config lookup to Rust. valueFor returns the value part of the line whose name matches key, or nothing. Return a &str that borrows from the lines without copying, and work out which parameter it needs a lifetime on.

    Starting code in TypeScript
    config.ts
    function valueFor(lines: string[], key: string): string | undefined {
      for (const line of lines) {
        const eq = line.indexOf("=");
        if (eq !== -1 && line.slice(0, eq).trim() === key) {
          return line.slice(eq + 1).trim();
        }
      }
      return undefined;
    }
    
    const lines = ["host = example.com", "port = 8080"];
    for (const key of ["port", "user"]) {
      console.log(`${key}: ${valueFor(lines, key) ?? "missing"}`);
    }
    Starting code in C#
    Config.cs
    string[] lines = ["host = example.com", "port = 8080"];
    foreach (var key in new[] { "port", "user" })
    {
        Console.WriteLine($"{key}: {ValueFor(lines, key) ?? "missing"}");
    }
    
    static string? ValueFor(string[] lines, string key)
    {
        foreach (var line in lines)
        {
            var eq = line.IndexOf('=');
            if (eq != -1 && line[..eq].Trim() == key)
            {
                return line[(eq + 1)..].Trim();
            }
        }
        return null;
    }

    Expected output

    port: 8080
    user: missing
    Show a hint

    The result is part of one of the lines, so it borrows from lines and not from key. Give lines and the result the same lifetime 'a, and leave key without one. split_once('=') splits a line into a name and a value.

    Show a solution
    fn value_for<'a>(lines: &'a [String], key: &str) -> Option<&'a str> {
        for line in lines {
            if let Some((name, value)) = line.split_once('=')
                && name.trim() == key
            {
                return Some(value.trim());
            }
        }
        None
    }
    
    fn main() {
        let lines = vec![
            String::from("host = example.com"),
            String::from("port = 8080"),
        ];
        for key in ["port", "user"] {
            println!("{key}: {}", value_for(&lines, key).unwrap_or("missing"));
        }
    }

    value_for returns a borrow into one of the lines, so its signature ties the result to lines with 'a. key is only compared, so it gets no name and the caller can free it straight away. Option<&'a str> is the Rust form of a string that might be missing. Nothing is copied: each value is a slice of a line.

    Saved in this browser only.