Skip to content
Free public beta until December 4, 2026: every course is open, no card needed. After that, the first chapter of each course stays free and full access is a one-time $39 ($19 for up to 100 founding members chosen for helpful feedback). Your progress is kept. How the beta works

Recipe

Annotate a function that returns a reference

Use when: rustc reports E0106 on a function with two or more reference inputs and a reference output

Goal: a signature whose lifetimes say exactly which inputs the result borrows from

Taught in Annotating functions

  1. 1

    Read the body and list every input whose data can be returned, on any path.

    Example

    In before(text, marker), both arms return part of text. The list is just text.

    Why: the signature has to describe what the body really does, and only you (not the compiler) read the body to write it.

  2. 2

    Add <'a> after the function name.

    Why: a lifetime parameter must be declared before the signature can use it, like <T>.

  3. 3

    Write &'a on each input from step 1 and on the returned reference. Leave the other inputs as plain &T.

    Example

    fn before<'a>(text: &'a str, marker: &str) -> &'a str

    Why: shared names say "the result is valid only while these inputs are"; an input left unnamed gets its own separate region.

  4. 4

    An error in the body means it returns data the signature doesn't allow. E0597 at a call means a caller uses the result after an input is gone.

    • error in the body — fix the body, or add that input to 'a if it really can be returned.
    • E0597 at a call — fix the call: owner outward, use sooner, or copy.

    Why: the signature is the contract both sides are checked against, so each error tells you which side broke it.

Common mistakes

  • Putting 'a on every input by habit, which makes correct calls fail.
  • Changing the signature to silence an E0597 at a call site.
  • Expecting 'a to keep an argument alive for longer.