Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 132 ยท Ownership and Borrowing

Lifetime Patterns and Pitfalls

Practical Rust lifetime patterns: returning references, why self-referential structs fail, T: 'a bounds, the '_ lifetime and owning vs borrowing.

You know what a lifetime is and how to annotate one. This lesson is the field guide: the situations in which lifetimes show up in real code, the shapes that work, the shapes that cannot work (and why), and how to choose between a borrowing design and an owning one. It also introduces three pieces of syntax you will meet in library code: T: 'a bounds, the anonymous lifetime '_, and higher-ranked trait bounds (for<'a>).

If any of this feels shaky, review Lifetimes first.

Pattern 1: return a reference into your input

The most common safe pattern is "give back a piece of what you were given". The elision rules handle the simple cases, and the compiler guarantees the caller cannot invalidate the piece while it is in use:

Rust Returning pieces of the input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Zero allocation, zero copying. This is how Rust parsers and tokenizers get their speed. The price is that line cannot be changed or dropped while k and v are alive.

Pattern 2: you cannot return a reference to something you created

If the data is created inside the function, nobody owns it after the function returns. Return an owned value instead:

Rust Returning a reference to a local (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

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

The compiler fully understands the cause: loud is dropped at the closing brace. The fix is to return String. A rule of thumb for every function: if the result is new data, return it owned; if the result is a part of the input, return a reference. Sometimes the same function can do both, using Cow (see Copy, Clone and Move Semantics).

Rust The fix: return an owned String

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Pattern 3: iterators and structs that borrow

An iterator over a collection usually borrows it. The type often hides a lifetime, which you can see by writing the return type of a function that returns an iterator:

Rust Returning an iterator that borrows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Two details worth studying:

  • In Words, the associated type is Item = &'a str with the struct's lifetime 'a, not the lifetime of &mut self. That is what lets you collect all the words and keep them after the iterator is gone. If next returned data tied to &mut self, each item would have to be dropped before the next call, which is the problem of lending iterators, and the standard Iterator trait cannot express it.
  • + '_ on impl Iterator says "this iterator may borrow from the arguments". In the 2024 edition, impl Trait in return position automatically captures all in-scope lifetimes, so you can often write simply impl Iterator<Item = &i32>. The explicit + '_ is still accepted and makes the intent obvious.

The anonymous lifetime '_

'_ means "a lifetime, but I will not name it, infer it". It is useful where hiding a lifetime would be confusing but naming it adds nothing:

Rust '_ in impl blocks and return types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You have seen Formatter<'_> in every Display implementation. Label<'_> in a return type tells the reader "this holds a borrow of the input", where a bare Label would hide that. Newer Rust versions warn about hidden lifetimes in paths under the elided_lifetimes_in_paths lint, which you can enable to catch them.

Pattern 4: lifetime bounds, T: 'a

Sometimes a generic type must not contain references that die too soon. A lifetime bound T: 'a says "every reference inside T lives at least as long as 'a". It appears when a struct stores a reference to a generic type:

Rust A bound on a generic referent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Since Rust 2018 the compiler infers T: 'a for you in a struct like Cache, so writing it is optional there. You still write bounds yourself on functions that store things for a while: fn spawn<F: FnOnce() + Send + 'static>(f: F) means "the closure holds no short-lived borrows", which is why you must move owned data into a thread (see Threads).

A bound can relate two lifetimes with 'b: 'a ("'b outlives 'a"):

Rust 'b: 'a, one lifetime outlives another

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You rarely need this, because the compiler already knows a longer-lived reference can stand in for a shorter-lived one (subtyping of lifetimes). It appears in a few advanced APIs and in error messages that mention "lifetime may not live long enough".

Pattern 5: self-referential structs (and why not)

A tempting idea: a struct that owns a String and also stores a &str pointing into it.

Rust A struct that borrows from itself (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler rejects it with two errors: E0515 ("cannot return value referencing local variable") and E0505 ("cannot move out of text because it is borrowed"). The second is the heart of the matter: title borrows text, and a borrowed value cannot be moved, yet building the struct moves text into it. Even for a struct you build without a function, moving it later is the problem: a move copies the struct's bytes to a new address, but a reference stored inside would still point at the old one. The language cannot tell the safe cases (a String's heap buffer does not move) from the unsafe ones (an inline array does), so it rejects the shape.

Everyday solutions, from best to worst:

  1. Store ranges or indices instead of references. Keep the String and store title: Range<usize>; produce the &str on demand.
  2. Split the type in two: an owner (holds the data) and a view (borrows from it), and let the caller keep the owner alive.
  3. Use Rc<str> / Arc<str> (shared ownership) when several parts need the same text.
  4. Only if you must, use Pin and unsafe code, or a crate like ouroboros (read-only mention, not available here). Pin, Unpin and Self-Referential Types shows why Pin exists, and async blocks are the main place where the compiler itself generates self-referential values.
Rust Indices instead of self-references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Pattern 6: higher-ranked trait bounds (a preview)

Occasionally a closure or function must work for every possible lifetime, not one specific 'a. That is written for<'a> and called a higher-ranked trait bound (HRTB):

Rust A higher-ranked bound: a closure that accepts any borrow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You almost never write for<'a> yourself: for Fn(&str) -> &str the compiler adds it automatically through elision, so F: Fn(&str) -> &str means the same thing. You will see it in trait-object types such as Box<dyn for<'a> Fn(&'a str) -> &'a str> and in error messages like "expected closure signature for<'a> fn(&'a str)". The practical lesson: when the compiler complains that a closure is "not general enough", the closure was inferred for one specific lifetime. Adding the type annotation to its parameter (|s: &str| s.trim()) usually fixes that.

Owning versus borrowing: how to decide

Lifetimes spread. A struct Parser<'a> forces fn make() -> Parser<'a>, struct App<'a> { parser: Parser<'a> } and so on up the call chain. Use this guide:

Situation Prefer Why
Short-lived view over data you already have (a parser, a tokenizer, a function argument) Borrow (&'a str, &[T]) No allocation; the view dies with its scope
Data stored in long-lived structures, caches, app state, entities Own (String, Vec<T>) No lifetime parameters leaking everywhere
Data crossing threads, or returned from the function that built it Own, or Arc Spawned work may outlive the creator
Many owners of the same read-only data Rc<str> / Arc<str> / Rc<T> Cheap clones, no lifetimes
Either, depending on runtime input Cow<'a, str> Borrows when possible, owns when it had to change the text
Hot loops where profiling shows the copy matters Borrow Measure before choosing the more complex design

Beginners often over-use references. If you find yourself writing <'a> on five structs in a row, take a step back: cloning a String once at the edge of the program is typically far cheaper than the complexity cost. A good progression is to start with owned types, then switch hot spots to borrowing when a profiler says so.

Rust The same record, owned and borrowed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Common mistakes

  • Adding 'static to make errors disappear. It usually moves the problem; a &'static requirement means you must own the data or leak it.
  • Using the same 'a for everything. If inputs are unrelated, separate lifetimes keep the caller free (see the 'text/'pattern example in Lifetimes).
  • Returning references to temporaries. fn f() -> &str { &String::new() } cannot work; return String.
  • Fighting with &mut self methods that return references. A method fn get(&mut self) -> &T keeps self mutably borrowed for as long as the result lives. If you only read, take &self.
  • Expecting the borrow checker to understand function bodies across calls. It uses signatures. If a function's signature says the output borrows all of self, then the compiler assumes so even when only one field is used; write a method on the field or return the field.

Most lifetime errors disappear when you answer one question: who owns this data, and which scope keeps it alive? Once the owner is clear, the references follow.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which return type is valid for fn make(text: &str) -> ??? when the function builds a brand new uppercase string?

    New data created inside a function has no owner after the function returns, so it must be returned owned.
  2. 2. What does Label<'_> mean in an impl header or return type?

    '_ is the anonymous lifetime. It tells the reader a borrow is involved without inventing a name for it.
  3. 3. Why can a struct not safely hold a String and a &str pointing into that same String as ordinary fields?

    A borrow of a value locks that value in place, which conflicts with moving the struct, so safe Rust rejects self-referential structs. Use indices, split owner and view, or Pin with unsafe.
  4. 4. What does F: for<'a> Fn(&'a str) -> &'a str require of the closure?

    A higher-ranked bound quantifies over all lifetimes, so the function can call the closure with unrelated borrows.
  5. 5. A long-lived application state struct keeps user names. What is the usual best field type?

    Owned data keeps lifetime parameters from spreading through the program and allows the struct to be moved and sent across threads freely.

Summary

  • Return a reference when the result is part of the input; return an owned value when the result is new data.
  • '_ is the anonymous lifetime: write it where a lifetime exists but needs no name (impl Display for Label<'_>, Formatter<'_>, fn f(s: &str) -> Label<'_>).
  • T: 'a says the type holds no references that die before 'a; 'b: 'a says 'b outlives 'a. T: 'static means "contains no short-lived borrows".
  • Self-referential structs cannot be written with ordinary references. Store indices or ranges, split owner and view, use Rc/Arc, or reach for Pin and unsafe as a last resort.
  • for<'a> higher-ranked bounds mean "for every lifetime"; the compiler adds them for Fn(&str) -> &str automatically.
  • Own data in long-lived structures and across threads; borrow in short-lived views, parsers and hot paths; use Cow when it depends.

Next: Box and the Heap