MARY.WIN

RUSTY — LARAVEL TO RUST — 05

Lifetimes
without mysticism

Return a borrowed view with an honest validity relationship.
Tutorial 5 of 16 in From Laravel to Rust. Before you start: References and ownership.

What must remain valid when a function returns borrowed text? In examples/src/bin/ep05.rs, title() returns a view into an Action. The choose() function can return either of two borrowed strings. Their signatures describe which input storage must support the returned reference.

main() owns the action and fallback values. The call choose(title(&action), &fallback) borrows from both values. Neither function needs to allocate a replacement string for the displayed label.

This lesson covers what a lifetime annotation says: how long a returned reference may be used, relative to the inputs it might borrow from. We'll read one elided signature, one named lifetime 'a, and one function the compiler refuses with E0515. It leaves out lifetimes on structs beyond a mention, and variance entirely. It assumes Tutorials 1 to 4. The Laravel version of the problem is a DTO that looks independent while still containing references to mutable objects; in Rust that dependence gets written into the type.

Take a look at Example 1.

Example 1. Complete example (examples/src/bin/ep05.rs)

struct Action { title: String }

fn title(action: &Action) -> &str {
    &action.title
}

fn choose<'a>(preferred: &'a str, fallback: &'a str) -> &'a str {
    if preferred.is_empty() { fallback } else { preferred }
}

fn main() {
    let action = Action { title: "Run tests".into() };
    let fallback = String::from("Unnamed action");
    let label = choose(title(&action), &fallback);
    assert_eq!(label, "Run tests");
    assert_eq!(choose("", &fallback), "Unnamed action");
    println!("label: {label}");
}

Run it from the examples/ directory.

Expected output:

TERMINAL
cargo run --quiet --bin ep05
label: Run tests

There are two functions to read. title(action: &Action) -> &str has one input reference, and lifetime elision links the returned reference to that input without our having to name the relationship. The expression &action.title borrows the title stored in the supplied action, so the caller must keep that storage valid while it uses the returned view. choose names the shared relationship 'a: both parameters and the return type are &'a str. The if preferred.is_empty() branch selects fallback, and the other branch selects preferred, so the returned view is constrained by both inputs at the call.¹

Why does the compiler need the interface?

Sometimes a caller keeps a result after one of the inputs is gone, and the function might have returned a reference to exactly that input. The signature has to let the compiler judge the call without assuming a favorable branch in the body. Even when preferred is visibly nonempty at one call site, this signature still permits either input to come back. If you want a function that always returns a view of the first input, express that narrower relationship. Publish what callers can rely on.

The return that cannot work

make_title declared that it would return a &'a str, for any 'a the caller cared to name. Inside, it built a String on line 2 and returned a reference to it on line 3. The String belonged to the function and was due to be dropped at the closing brace, one line later. The compiler reported E0515.

Take a look at Example 2, which is that function.

Example 2. Returning a reference to a local (examples/compile-fail/fail05.rs, compiler refusal)

fn make_title<'a>() -> &'a str {
    let title = String::from("Run tests");
    &title
}

fn main() { println!("{}", make_title()); }

Compile it from the examples/ directory and inspect E0515, returning a reference to local data:

TERMINAL
rustc --edition=2024 compile-fail/fail05.rs
error[E0515]: cannot return reference to local variable `title`
 --> compile-fail/fail05.rs:3:5
  |
3 |     &title
  |     ^^^^^^ returns a reference to data owned by the current function

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0515`.

The local title owns a newly allocated String, and make_title tries to return &title. Returning from make_title drops that local string, so the caller cannot retain a valid view of its text. E0515 identifies exactly that: the attempted return of a reference to local data.

There are two repairs, and both are ownership choices. If the caller needs independent text, change make_title to return String; the return transfers ownership to the caller. You can also go the other way: if the caller already owns suitable text, accept that storage by reference and return a view into the supplied storage, as title does in Example 1.

When is a borrowed view the right result?

A borrowed view can be efficient and expressive: a search result might borrow titles from a catalog while rendering a list, with no independent String created. But a result that must outlive the catalog, or cross into a long-lived task, or stay unchanged through future edits, is usually easier to express as an owned value, and when a signature has grown three lifetime names and still will not compile it is, more often than the annotation's reputation suggests and less often than a tired reader would like, the program reporting that a temporary view is being asked to behave like durable data, which is a design fact.

That does not make ownership the better default. Copying a large dataset for a brief calculation may be unnecessary. If you're unsure, I'd ask whether the answer is consumed while the source is still available, or retained independently.

What 'static means

'static appears in two different contexts. A reference like &'static str can refer to text valid for the entire program, such as a string literal. A bound such as T: 'static means the type contains no non-static borrowed references that would expire; an owned String satisfies that bound and is still dropped normally.²

So choose compiles and both assertions pass. Now take one DTO from your Laravel application. Which objects does it still point at? Could one of them change after the DTO is built? Is that dependence what the application needs, or only what the constructor happened to receive?

Testing

In Example 1, create fallback inside a smaller block. Call choose inside that block, then try to use the returned label outside it. Before you compile the variation, write down your prediction: does the signature let the label outlive fallback?

The compiler rejects a label whose validity may depend on the expired fallback. You have three repairs: use the result within the block, extend the owner's scope, or create an owned result.

For a second case, write fn fixed_title() -> &'static str that returns the literal "Run tests". The literal supports that reference lifetime. A string created locally with format!(...) does not support the same borrowed return; that is the situation in Example 2.

Last, close this page and reconstruct choose from its two inputs and its two branches. Explain why the returned view may depend on fallback even when one particular call supplies a nonempty preferred title. Then run Example 1 to check the working case: the assertion accepts Run tests, and the terminal prints label: Run tests.

TL;DR

A lifetime describes how long borrowed access may remain valid relative to its sources. Elision links title's returned reference to its one input; 'a names the relationship in choose, where either of two inputs could come back, so the result is constrained by both. An annotation cannot keep a dropped value alive, which is E0515, and the repair is an ownership choice: return a String, or borrow storage the caller already owns. A borrowed view suits an answer consumed while its source is available. &'static str and T: 'static mean different things. Next: the ordinary case where the action is not there.

¹ The two original strings can still have different creation and drop points. 'a does not require them to be created together or dropped on the same line.

² This matters when spawning tasks in Tutorial 11. A bound does not instruct the runtime to leak the task or keep every owned allocation forever. Do not add 'static because an error message contains it; ask where the data is owned.

The sources.

Every program, its output and every compiler message were recorded on rustc 1.100.0 on 2026-11-20. Each page lists what was not checked.

Rust Book, Validating References with Lifetimes; Tokio tutorial, Spawning, for the 'static task-bound distinction.

NOT CHECKED — 4
  • That the compiler rejects a label used outside the block where fallback was created. This exercise is not among the checks run for this edition.
  • That fixed_title returning the literal "Run tests" is accepted, and that a reference to a locally created format!(...) string cannot be returned.
  • The Laravel DTO comparison. No Laravel application was run.
  • The reference links were not opened for this page.