rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
97.51k stars 12.61k forks source link

Return-type impl Trait lifetime bug? #131489

Closed contramundum53 closed 2 hours ago

contramundum53 commented 2 hours ago

I tried this code:

trait Iterable{
    // 'static is added here to restrict the returned iterators to be "owning iterators"
    fn owned_iter(&self) -> impl Iterator<Item=usize> + 'static;
}
struct B<T>{
    x: T,
}
impl <T: Iterable + Clone> Iterable for B<T>{
    fn owned_iter(&self) -> impl Iterator<Item=usize> + 'static {
        let y = self.x.clone();
        y.owned_iter()  // error[E0597]: `y` does not live long enough
    }
}

I expected to see this happen: It should compile, because y.owned_iter() is 'static and does not contain reference to y.

Instead, this happened:

 Compiling playground v0.0.1 (/playground)
error[E0597]: `y` does not live long enough
  --> src/lib.rs:12:9
   |
10 |     fn owned_iter(&self) -> impl Iterator<Item=usize> + 'static {
   |                   - let's call the lifetime of this reference `'1`
11 |         let y = self.x.clone();
   |             - binding `y` declared here
12 |         y.owned_iter()  // error[E0597]: `y` does not live long enough
   |         ^-------------
   |         |
   |         borrowed value does not live long enough
   |         argument requires that `y` is borrowed for `'1`
13 |     }
   |     - `y` dropped here while still borrowed

For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` (lib) due to 1 previous error

Rust Playground

If I use associate type manually, it compiles. (Rust Playground)

trait Iterable{
    type Iter: Iterator<Item=usize> + 'static;
    fn owned_iter(&self) -> Self::Iter;
}

struct B<T>{
    x: T,
}
impl <T: Iterable + Clone + 'static> Iterable for B<T>{
    type Iter = T::Iter;
    fn owned_iter(&self) -> Self::Iter {
        let y = self.x.clone();
        y.owned_iter()
    }
}

Meta

It happens on 1.83.0-nightly build, 2024-10-09 eb4e234...

contramundum53 commented 2 hours ago

Is duplicate with #131490 (@cdhowie filed the same bug report from my SO question)