Module 9 · Lesson 13 of 112

Lifetimes and lifetime elision

Explain why Rust checks reference lifetimes, expand elided signatures, and write functions and structs that borrow from existing data.

  • Beginner to advanced
  • 8 min read
  • 18 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, with the Rust toolchain and Cargo from the earlier setup lesson

Your place in the module
By the end you can 4 objectives
  • Explain which input borrows constrain the result of longest.
  • Expand elided lifetime annotations in functions and methods.
  • Define a struct that borrows a string slice from an external owner.
  • Implement a safe slice split and explain the invariants behind its unsafe block.
Video coming soonLifetimes and lifetime elision
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Reading borrow errors and choosing signatures
  • A shared borrow and an exclusive mutable borrow of the same data cannot overlap.
  • In straight-line code, a shared borrow can end after its last use even while its binding is still in scope.
  • An owned result derived from a shared reference can be used after the borrow ends.
01

Why references have lifetimes

4 min read

You have been reading borrow errors and writing reference parameters. This lesson answers why those references carry lifetimes and what the elision rules hide.

A Linux service can read bytes into an owned buffer and then inspect fields through borrowed slices. The standard library's slice documentation describes operations over this kind of borrowed data, including splitting a mutable buffer into two regions. For text, imagine a service that keeps a device label as a &str into a String containing a configuration line. If the service drops that String and later reads the label, the slice would refer to storage that is no longer valid. A reference in that state would be a . Rust checks the lifetime of the borrow so safe code cannot reach that read.

A lifetime describes where a reference must be valid for the uses that the program makes of it. The compiler can often see that a borrow ends at its last use, before the closing brace of the block containing the reference variable. The owner and the borrow therefore have different durations. A buffer can exist for an entire function while a borrow of one line lasts only until that line is printed. In a signature, the lifetime matters because code using the function needs to know which data must remain valid after the call.

Consider a function that returns either of two input strings. Both branches return a borrowed slice. The caller needs a single contract that works for either branch.

rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() >= y.len() {
        x
    } else {
        y
    }
}

The <'a> after longest declares a lifetime parameter. Each &'a str requires a string slice valid for 'a. The returned slice is also valid for 'a, so the caller can use it wherever that common lifetime permits. The arguments may come from owners with different scopes. Rust can use shorter borrows of both inputs for the call. The requirement is that both inputs are valid throughout the lifetime needed by the returned slice.

Here len() compares byte lengths, and a tie selects x. The comparison decides which slice the program returns at run time. The lifetime relationship is checked at compile time from the signature. An annotation leaves both owners' drop points as determined by the program. It also cannot make a reference to a local String valid after the function returns. A function that creates a new string and wants the caller to keep it can return an owned String.

Validity of the result from longestBorrow bothstringsCalllongestUse resultBothstrings arevalidDrop innerstringLater userejectedBorrow bothstringsCalllongestUse resultBothstrings arevalidDrop innerstringLater userejected
The returned reference can be used only where both input borrows permit it
rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() >= y.len() { x } else { y }
}

fn main() {
    let configured = String::from("temperature");
    let selected;

    {
        let detected = String::from("temp");
        selected = longest(&configured, &detected);
        assert_eq!(selected, "temperature");
    }

    // A use of selected here would make the borrow outlast detected.
}

The assertion inside the inner block is valid because both strings are still available there. If you add another assertion after the block, detected would be dropped before that second use, and rustc 1.100.1 rejects it:

text
error[E0597]: `detected` does not live long enough
  --> src/main.rs:9:41
   |
 8 |         let detected = String::from("temp");
   |             -------- binding `detected` declared here
 9 |         selected = longest(&configured, &detected);
   |                                         ^^^^^^^^^ borrowed value does not live long enough
10 |         assert_eq!(selected, "temperature");
11 |     }
   |     - `detected` dropped here while still borrowed
12 |     assert_eq!(selected, "temperature");
   |     ----------------------------------- borrow later used here

The compiler applies the function's declared relationship even though a reader can tell which string is longer in this particular example. Moving the use inside the block repairs the borrow. If the program needs the selected text after the block, it can call to_owned() on the result inside the block and keep the resulting String.

02

What lifetime elision infers

3 min read

A function that trims text has one borrowed input. These two definitions express the same lifetime relationship. They are shown under different names so they can appear in the same file.

rust
fn clean(line: &str) -> &str {
    line.trim()
}

fn clean_explicit<'a>(line: &'a str) -> &'a str {
    line.trim()
}

The returned slice borrows from line, so a caller can use it within the borrow of that input. trim() returns a slice of the input text. Reading the signature is enough to determine the lifetime the caller may rely on.

Step by stepExpand the omitted lifetimes
  1. Give each elided lifetime in the parameters its own lifetime parameter. In fn same(x: &str, y: &str) -> bool, the two input references have separate lifetimes.

  2. If there is exactly one distinct input lifetime, assign it to every elided output lifetime. In fn clean(line: &str) -> &str, the output receives the lifetime of line. The rule also works when multiple inputs explicitly use the same lifetime.

  3. In a method with an &self or &mut self receiver, assign the receiver reference's lifetime to any elided output lifetimes. This also resolves the output when another parameter has a different lifetime.

The output rules apply to omitted output lifetimes wherever they occur in this kind of signature. For example, fn fields(line: &str) -> (&str, &str) gives both returned slices the input lifetime. An explicitly written output lifetime expresses the relationship written in the signature. A function returning bool has no borrowed output to resolve, so its input references can have separate inferred lifetimes without any ambiguity.

The proposed signature fn longest(x: &str, y: &str) -> &str fails with error E0106, "missing lifetime specifier". rustc 1.100.1 adds the note "this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from x or y". The parameter rule introduces separate input lifetimes, there is no receiver, and neither output rule picks a lifetime. The compiler does not inspect the branches to invent a public contract. The same ambiguity occurs even if a free function with that signature always returns its first argument. If the first input alone supplies the result, fn first<'a>(x: &'a str, _y: &str) -> &'a str expresses that fact. In a call to first, the second borrow can end while the result is still usable.

Elision for borrowed return valuesSignaturepatternElided returnOne inputlifetimeclean(line:&str)InputlifetimeBorrowedreceivername_or(&self, fallback:&str)ReceiverlifetimeTwo elidedinputslongest(x:&str, y:&str)Explicitannotationrequired
The origin of an elided return lifetime follows from the signature

The receiver rule affects what callers can do with methods. Suppose a method has the signature fn name_or(&self, fallback: &str) -> &str. The elided return is tied to the borrow of self. The signature alone gives the method no guarantee that fallback lives that long, so returning fallback directly would fail to compile. Similarly, fn bytes(&mut self) -> &mut [u8] ties the returned slice to the mutable receiver borrow. If the caller still plans to use the slice, another access that conflicts with that borrow must wait.

03

Reference fields and disjoint borrows

3 min read
rust
struct Foo<'a> {
    r: &'a str,
}

impl<'a> Foo<'a> {
    fn view(&self) -> &str {
        self.r
    }

    fn source(&self) -> &'a str {
        self.r
    }
}

Foo<'a> contains a slice that is valid for 'a. When you construct Foo { r: &line } from a String named line, the field borrows the string data. If you then try to use Foo or its field after line is dropped, Rust rejects the program. The struct can be dropped earlier than the data it borrows. Moving the struct to another variable moves the stored reference along with it. The data still belongs to line.

Borrowed text in a structString ownstextFoo storesslicesourcecopiesreferenceFoo leavesscopeSlice stillusableString isstill validString ownstextFoo storesslicesourcecopiesreferenceFoo leavesscopeSlice stillusableString isstill valid
The input String owns the text that the Foo field borrows

A reference to the struct creates a separate borrow. In view, the output lifetime is elided, so &self determines how long callers may use the returned slice. In source, the output lifetime is explicit and comes from the stored field. Since a shared string reference can be copied, source can return that reference with its original lifetime. The following code can use the result after the local Foo goes out of scope, because line is still alive.

rust
fn main() {
    let line = String::from("sensor");
    let label = {
        let record = Foo { r: &line };
        record.source()
    };
    assert_eq!(label, "sensor");
}

(This main goes in the same file as the Foo definition above.)

Changing source() to view() makes this code fail. The signature of view restricts the result to the borrow of record, which ends inside the block. Putting the assertion inside the block would satisfy that signature. When reviewing a borrowed struct, distinguish the lifetime on its type from the lifetime of a reference to one instance. The method names here illustrate two contracts that the same field can support.

Going deeperExplore the mechanism

Lifetime relationships tell the compiler how long references must remain valid. For mutable references it must also establish that their accesses obey exclusivity. Consider the two ranges [..mid] and [mid..] of one mutable slice. A programmer can see that these ranges are disjoint when mid <= len. Two separate mutable indexing expressions still borrow through the same slice, and the borrow checker does not use that arithmetic relationship to permit both borrows. An assertion about mid makes the boundary condition explicit to readers and checks it at run time. It does not establish range disjointness for the borrow checker.

The standard slice method split_at_mut provides a safe interface for this case, as described in the standard library's slice documentation. The method returns the prefix ending just before mid and the suffix beginning at mid. Both results are borrowed from the same input. They can coexist because they grant mutable access to disjoint sets of elements.

rust
fn split_at_mut_style<T>(buf: &mut [T], mid: usize) -> (&mut [T], &mut [T]) {
    let len = buf.len();
    assert!(mid <= len);
    let ptr = buf.as_mut_ptr();

    // SAFETY: Both ranges come from buf and share no elements.
    // The check permits a one-past pointer only for an empty suffix.
    unsafe {
        (
            std::slice::from_raw_parts_mut(ptr, mid),
            std::slice::from_raw_parts_mut(ptr.add(mid), len - mid),
        )
    }
}

The outer function is safe to call. Its check rejects an invalid split index before pointer arithmetic or slice construction. The original slice guarantees a non-null, aligned pointer and valid backing storage for its elements. The prefix covers [0, mid) and the suffix covers [mid, len). Together they use the existing elements once each. At mid == 0 the prefix is empty. At mid == len the suffix is empty, and the computed pointer may be one past the last element. The code never dereferences that pointer for an element of the empty suffix. The same index check allows only mid == 0 for an empty input.

The unsafe block is where the implementation proves the conditions that safe indexing alone could not convey to the compiler. from_raw_parts_mut trusts its caller to supply valid memory and enforce exclusivity for the resulting borrow. The implementation derives both pointers from the original mutable slice, accesses no elements through that original slice while the results are live, and exposes the results through a signature that ties both output lifetimes to the sole input borrow. In ordinary code, calling buf.split_at_mut(mid) uses the standard library's implementation of this contract.

Sometimes the need is to mutate through a shared reference, such as incrementing a diagnostic counter in a method that takes &self. addresses that case. A Cell<u32> can update a counter with get and set without handing out a mutable reference to its contents. A RefCell<T> checks shared and exclusive borrows at run time. A conflicting call to borrow_mut() panics while an earlier borrow is still active. These types enforce their own access rules. Disjoint mutable views into one buffer call for a slice split, whose safety depends on the element ranges.

When deciding what a signature promises, identify the owner of each returned reference and where the result needs to be used. The next lesson, 'static, multiple lifetimes, and iterator invalidation, applies that reasoning to longer-lived data, signatures that preserve independent lifetimes, and changes to a collection while it is borrowed.

Key takeaways

  • Lifetime annotations express validity relationships that Rust checks at compile time.
  • Elision assigns omitted input lifetimes and derives omitted output lifetimes using fixed signature rules.
  • A reference field requires its referent to remain valid wherever the field is used.
  • A safe slice split validates the boundary before constructing two disjoint mutable slices.
Reflect
  1. Explain to a colleague, in two sentences: explain which input borrows constrain the result of longest.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close