Skip to content

impl Trait return value causes an over-restricted lifetime requirement #51069

Closed
@cuviper

Description

@cuviper

Reduced from an example given on the users forum.

This code (playground) fails to compile:

fn main() {
    let v = vec![""];
    runner(&v);
}

fn runner<'p>(v: &Vec<&'p str>) -> impl Iterator<Item = &'p str> {
    find(&vec![0], v)
}

fn find<'n, 'p, I, S>(_: &'n I, _: &Vec<&'p str>) -> impl Iterator<Item = &'p str>
where
    &'n I: IntoIterator<Item = S>,
{
    std::iter::empty()
}
error[E0597]: borrowed value does not live long enough
 --> src/main.rs:7:11
  |
7 |     find(&vec![0], v)
  |           ^^^^^^^ temporary value does not live long enough
8 | }
  | - temporary value only lives until here
  |
note: borrowed value must be valid for the lifetime 'p as defined on the function body at 6:1...
 --> src/main.rs:6:1
  |
6 | fn runner<'p>(v: &Vec<&'p str>) -> impl Iterator<Item = &'p str> {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

It seems the 'n lifetime is getting tied into the return type somehow.

It works if you make find return an explicit type:

fn find<'n, 'p, I, S>(_: &'n I, _: &Vec<&'p str>) -> std::iter::Empty<&'p str>
where
    &'n I: IntoIterator<Item = S>,
{
    std::iter::empty()
}

It also works if you instead remove the S parameter:

fn find<'n, 'p, I>(_: &'n I, _: &Vec<&'p str>) -> impl Iterator<Item = &'p str>
where
    &'n I: IntoIterator,
{
    std::iter::empty()
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-impl-traitArea: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch.C-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