Lifetime issue migrating from 2021 to 2024

The following code compiles in edition 2021 but fails in edition 2024:

fn main() {
    for a in a_iter(Foo) {
        println!("{a}");
    }
}

struct Foo;

fn a_iter(foo: Foo) -> impl Iterator<Item = i32> {
    foo.b_iter()
}

impl Foo {
    fn b_iter(&self) -> impl Iterator<Item = i32> {
        [1, 2, 3].into_iter()
    }
}

You can test it in the playground here:
Rust Playground (runs, 2021)

Rust Playground (fails, 2024)

Now, I know I might change it to a_iter(foo: &Foo), a_iter(foo: Arc<Foo>) or b_iter(self), but is there a way to make it work again with the current signature?

You need to add an empty use bound (details):

 impl Foo {
-     fn b_iter(&self) -> impl Iterator<Item = i32> {
+     fn b_iter(&self) -> impl Iterator<Item = i32> + use<> {
         [1, 2, 3].into_iter()
     }
 }
4 Likes

You can add

#![warn(rust_2024_compatibility)]

and it gives you the answer:

warning: `impl Iterator<Item = i32>` will capture more lifetimes than possibly intended in edition 2024
  --> src/main.rs:16:25
   |
16 |     fn b_iter(&self) -> impl Iterator<Item = i32> {
   |                         ^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = warning: this changes meaning in Rust 2024
   = note: for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2024/rpit-lifetime-capture.html>
note: specifically, this lifetime is in scope but not mentioned in the type's bounds
  --> src/main.rs:16:15
   |
16 |     fn b_iter(&self) -> impl Iterator<Item = i32> {
   |               ^
   = note: all lifetimes in scope will be captured by `impl Trait`s in edition 2024
note: the lint level is defined here
  --> src/main.rs:1:9
   |
1  | #![warn(rust_2024_compatibility)]
   |         ^^^^^^^^^^^^^^^^^^^^^^^
   = note: `#[warn(impl_trait_overcaptures)]` implied by `#[warn(rust_2024_compatibility)]`
help: use the precise capturing `use<...>` syntax to make the captures explicit
   |
16 |     fn b_iter(&self) -> impl Iterator<Item = i32> + use<> {
   |                                                   +++++++
5 Likes