Skip to content

RPIT with 'static bound captures lifetimes from generic arguments #106750

Closed as not planned
@jwong101

Description

@jwong101

I tried this code:

fn bar<T>(_i: T) -> impl Iterator<Item = usize> + 'static {
    std::iter::once(3)
}

fn bar2<T: ?Sized>(_i: &T) -> impl Iterator<Item = usize> + 'static {
    std::iter::once(3)
}

fn main() {
    let mut b;
    {
        let a = 1;
        // doesn't work
        b = bar(&a);
        
        // this works
        // b = bar2(&a);
    }
    println!("{}", b.next().unwrap());
}

I expected to see this happen:

Both bar and bar2 should compile successfully, since both outputs have 'static bounds.

Instead, this happened:

The version that calls bar2 successfully compiles, whereas calling bar results in the following error:

error[[E0597]](https://doc.rust-lang.org/nightly/error-index.html#E0597): `a` does not live long enough
  --> src/main.rs:27:19
   |
27 |         b = bar(&a);
   |                   ^^ borrowed value does not live long enough
28 |     }
   |     - `a` dropped here while still borrowed
29 |     println!("{}", b.next().unwrap());
   |                    -------- borrow later used here

Using a TAIT as the return type of bar seems to not capture any lifetimes from T.

#![feature(type_alias_impl_trait)]

type Iter = impl Iterator<Item = usize> + 'static;

fn bar<T>(_i: T) -> Iter {
    std::iter::once(3)
}
fn main() {
    let mut b;
    {
        let a = 1;
        // this works fine
        b = bar(&a);
    }
    println!("{}", b.next().unwrap());
}

Meta

rustc --version --verbose:

rustc 1.68.0-nightly (0442fbabe 2023-01-10)

This is also present on the latest stable version: rustc 1.66.1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-impl-traitArea: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch.A-type-systemArea: Type systemC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions