Abstractions in Practice · 18 min · free lesson

Generic Lifetimes

Combine type bounds with borrow relationships.

Core idea

A function may be generic over both a data type and a lifetime.

Left borrow lasts from time one to eight, right from four to eleven, and the returned borrow only from four to eight.
A generic return reference is valid only while both possible borrowed inputs remain valid.

Understand it

A function may be generic over both a data type and a lifetime. Keep each parameter only when the body needs it; extra bounds make an API less reusable without adding safety.

The choose signature has two independent kinds of abstraction. T: PartialOrd says what operation the body may perform on the values: comparison. 'a says how long the borrowed inputs and returned reference are related. These parameters solve different problems. Replacing the lifetime with a broader trait bound cannot make a dangling reference safe, and adding a lifetime cannot make an incomparable type satisfy PartialOrd.

The result borrows one of the two inputs. Because the body may choose either, the caller must use it only while both candidate sources are valid. Suppose the left value lives throughout a function and the right value lives in an inner block. Calling choose and using the result inside the block is fine. Keeping the result for use after that block is not, because it might point to the right value. The generic type does not change this rule; it applies whether T is an integer, a string wrapper, or a custom ordered type.

Try calling choose with two i32 values, then with a custom type that implements PartialOrd. Next, create one input in a smaller scope and observe the lifetime error when the result escapes it. Fix the use site, not the annotation label. Keep trait bounds as narrow as the implementation needs, and keep lifetime relationships as specific as the returned data requires. A clear signature explains both the operation and the ownership story.

The letter chosen for a lifetime has no special power. Rename it consistently and the contract is the same. The useful information is which references share the label and which output is tied to them.

Read the code

fn choose<'a, T>(left: &'a T, right: &'a T)
    -> &'a T
where T: PartialOrd {
    if left > right { left } else { right }
}

The example makes the contract visible in code.

Practise this code in Playground ↗

Try it

Say what T: PartialOrd and 'a each promise in choose.

What success looks like: You can call choose with two types, and show when its result stops being usable.

Check your understanding

What does 'a connect here?

Reveal the answer
  1. Both inputs and output
  2. Only T
  3. The PartialOrd impl

Correct: Both inputs and output.

Go deeper

Common misconception: “A stronger bound on T could make the returned reference live longer.”

T: PartialOrd only permits >, and 'a only ties both inputs to the result. Neither does the other's job, so no trait bound can keep the result valid once an input is gone.

  1. Separate the parameters: T: PartialOrd allows left > right. 'a says the returned reference is valid only while both inputs are, and it says nothing about the operations on T.
  2. Predict before checking: Predict whether choose(&1.5, &2.5) is accepted, given that f64 has no Ord. Then put right in an inner block and predict whether the result can be used after it.
  3. Compare with evidence: f64 compiles and returns 2.5, because only PartialOrd is required. Using the result after the block gets E0597; fix the use site, not the annotation.

Transfer challenge: Change the bound to T: Ord and read the E0277 that choose(&1.5, &2.5) gets. Then remove the bound entirely and read the error on left > right.

Connections

  • Default Trait Methods: Share behavior while allowing an override
  • Iterator Pipelines: Transform lazily, then choose one consumer
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Generic Lifetimes (courseId "ownership", lessonId "generic-lifetimes")
Link: https://crabrix.com/learn/ownership/generic-lifetimes/
Goal: A function may be generic over both a data type and a lifetime.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=ownership/generic-lifetimes) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.