skip to content

Migrating a Rust crate to the 2024 edition, why does `cargo fix --edition` append `+ use<>` to some `-> impl Trait` returns, and when can it not?

level: seniorimportance: should knowfreq 30%

answer

  1. which lifetimes the hidden type may use
  2. 2024 captures every in-scope lifetime
  3. the impl_trait_overcaptures lint
  4. anonymous parameters cannot be named

basics

~20 s

Rust 2024 makes a return-position impl Trait capture every in-scope lifetime. The impl_trait_overcaptures lint adds use<> (or use<T>) so the migrated return captures only what 2021 captured. It cannot when an argument-position impl Trait parameter would need naming.

solid answer

~40 s

On 2021, a return-position `impl Trait` in a free function or inherent method captured a lifetime only if it appeared in the bounds; type and const parameters were captured in every edition. Rust 2024 captures every in-scope lifetime, matching trait impls, trait definitions and `async fn`. So `fn snapshot(&self) -> impl Iterator<Item = u32>` now borrows `self` in the type system, and a caller that keeps the iterator after the registry is gone stops compiling. The `impl_trait_overcaptures` lint, applied by `cargo fix --edition`, appends a precise-capturing bound, `+ use<>` here, stable since Rust 1.82, to keep the 2021 set. It cannot when a parameter is written `impl Trait`: that anonymous type parameter cannot appear in `use<..>`, so the lint only warns and suggests naming it, which changes the API by allowing a turbofish.

code

rust · 17 lines
rust
struct Registry {
    ids: Vec<u32>,
}

impl Registry {
    fn snapshot(&self) -> impl Iterator<Item = u32> {
        self.ids.clone().into_iter()
    }
}

fn main() {
    let ids = {
        let registry = Registry { ids: vec![7, 9] };
        registry.snapshot()
    };
    println!("{:?}", ids.collect::<Vec<_>>());
}

go deeper

for a junior

Recall that Rust 2024 lets a returned impl Trait capture every lifetime in scope, and that cargo fix may add a use<> bound to keep older code compiling.

for a middle

Explain capture as the set of parameters the hidden type may use, the 2021 versus 2024 rule for free functions and inherent methods, and what use<..> from Rust 1.82 states.

for a senior

Show the migration review: which inserted use<> bounds keep callers compiling, how to handle the argument-position impl Trait warning, and why use<> on a borrowing body fails with E0700.

for a principal

Treat each use<> on a public API as a contract decision: it frees callers today but forecloses returning a borrowing type tomorrow, so set a rule for when a library keeps it.

## What capturing means A function returning `impl Trait` hides a concrete **hidden type** behind an **opaque type**. The opaque type **captures** some of the generic parameters in scope, and only captured parameters may appear in the hidden type. Capturing a lifetime has a cost for callers: the returned value is treated as possibly borrowing from that lifetime, so it cannot outlive it. Since **Rust 1.82** a `use<..>` bound states the set explicitly in every edition, as in `impl Iterator<Item = u32> + use<'a, T>`. Without one, the edition decides. | Where the return-position impl Trait appears | 2021: lifetimes captured implicitly | 2024: lifetimes captured implicitly | |---|---|---| | Free functions, inherent methods | Only those named in the bounds | All in scope | | Trait impls, trait definitions, `async fn` | All in scope | All in scope | | Type and const parameters (anywhere) | All in scope | All in scope | The 2024 edition made the first row consistent with the others. In most code that is what the author wanted, and the old workarounds disappear. ## What cargo fix inserts, and why The `impl_trait_overcaptures` lint, part of the `rust-2024-compatibility` group, finds returns that would capture more lifetimes on 2024 and, where it can, appends a `use<..>` bound listing exactly what 2021 captured: ```rust impl Registry { fn snapshot(&self) -> impl Iterator<Item = u32> + use<> { self.ids.clone().into_iter() } } ``` The hidden type is `std::vec::IntoIter<u32>`, which owns its data, so on 2021 a caller could build a `Registry` inside a block and return the iterator out of it. Without the added `use<>`, on 2024 that caller fails with E0597, "`registry` does not live long enough", and rustc notes that the call may capture more lifetimes than intended. The inserted bound is semantics-preserving: every caller keeps compiling. ## The case it cannot fix: argument-position impl Trait A parameter written `items: impl Iterator<Item = u32>` (**argument-position impl Trait**) introduces an anonymous type parameter. A `use<..>` bound must list every type parameter, because type parameters are always captured, but there is no way to name an anonymous one. So for ```rust fn tagged<'a>(prefix: &'a str, items: impl Iterator<Item = u32>) -> impl Iterator<Item = String> ``` the lint only warns that the return "will capture more lifetimes than possibly intended in edition 2024" and suggests rewriting the signature as `fn tagged<'a, T: Iterator<Item = u32>>(prefix: &'a str, items: T) -> impl Iterator<Item = String> + use<T>`. You have two choices: 1. **Name the parameter** and add `use<T>`. Callers that relied on the result not borrowing `prefix` keep compiling, but the function now accepts a turbofish, a small API change. 2. **Accept the new capture.** Any caller that passed a short-lived `prefix` and returned the iterator, for example with `+ 'static`, then fails, with E0515 in the case of a borrowed local. ## Keep the bound, or delete it? The inserted `use<>` is a decision, not boilerplate: - On a **public** function, `use<>` promises callers that the result never borrows the argument. Keeping it keeps that promise; widening the captures later can break callers that relied on it. - Deleting it reserves room for a future hidden type that does borrow. The edition guide suggests that when that flexibility matters more than the callers' freedom. - On private code, a `use<>` the compiler does not need is noise; the capture only matters where some caller outlives the borrow. - If the hidden type really borrows, `use<>` is wrong. A body returning `self.ids.iter().copied()` under `+ use<>` fails with E0700, "hidden type ... captures lifetime that does not appear in bounds", and needs `use<'_>` or no bound. ## The old tricks Before 1.82, code that needed a lifetime captured in a 2021 free function used the **outlives trick**, `impl Sized + 'a`, often with an extra `T: 'a` bound, or the **`Captures` trick**, a blanket helper trait used as `+ Captures<&'a ()>`. Both still compile on 2024, and there is no automatic migration for either. On 2024 they can usually be deleted outright, and in any edition replaced with `use<'a, T>`, which also removes the outlives trick's needless `T: 'a` restriction on callers. Callers' E0597 errors and the general rules of `impl Trait` belong to the material on `impl Trait`; this question is about what the migration writes and what you decide afterwards.

  • Why does the migration lint ignore `-> impl Trait` in trait impls and `async fn`?
    Those positions already captured every in-scope lifetime in all editions: return-position `impl Trait` in trait impls and trait definitions, and the future an `async fn` returns. The 2024 edition only brought free functions and inherent methods in line with them, so nothing else changes meaning and nothing needs a `use<..>` bound.
  • After migration, how do you choose between keeping `+ use<>` on a public function and deleting it?
    Keep it if callers benefit from the result not borrowing the arguments and the implementation will stay owned; it is part of the signature's promise. Delete it if a later version may want to return a borrowing iterator, because adding a capture afterwards can break callers. On private code, keep it only where some caller actually needs the iterator to outlive the borrow.

  • In 2024 every impl Trait return must spell out a use<..> bound
  • Rust 2024 stopped capturing type parameters in return-position impl Trait
  • cargo fix adds use<> so the hidden type may borrow self
  • use<..> bounds are an unstable feature that needs nightly
  • The Captures trick stops compiling once a crate moves to 2024

Assumes Rust 1.99 on the 2024 edition (stable since 1.85), whose lifetime capture rules differ from 2021; use<..> bounds have been stable in every edition since 1.82.