Skip to content

impl Trait causes "borrowed value does not live long enough" #50823

@cuviper

Description

@cuviper

This code:

fn main() {
    println!("{:?}", max());
}

fn max() -> Option<i32> {
    let v = vec![1, 2, 3];
    iter(&v).max()
}

fn iter(a: &[i32]) -> impl Iterator<Item = i32> + '_ {
    a.iter().cloned()
}

gives this error:

error[E0597]: `v` does not live long enough
 --> src/main.rs:7:11
  |
7 |     iter(&v).max()
  |           ^ borrowed value does not live long enough
8 | }
  | - `v` dropped here while still borrowed
  |
  = note: values in a scope are dropped in the opposite order they are created

But if I change the return type to an explicit std::iter::Cloned<std::slice::Iter<'_, i32>>, then it's fine. It's also fine if I bind that result before returning it, like: let m = iter(&v).max(); m

And it works with #![feature(nll)], so maybe I just have to hope for that to stabilize soon... 🙏

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-NLLArea: Non-lexical lifetimes (NLL)A-impl-traitArea: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch.C-bugCategory: This is a bug.T-langRelevant to the language teamfixed-by-NLLBugs fixed, but only when NLL is enabled.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions