Skip to content

improve error message when returning iterator with reference into stack frame  #53882

Open
@nikomatsakis

Description

@nikomatsakis

This example (playground):

use std::rc::Rc;

fn iterate(data: Rc<Vec<u32>>) -> impl Iterator<Item = u32> {
    data.iter().cloned()
}

fn main() {
    for x in iterate(Rc::new(vec![1, 2, 3])) {
        println!("Hi! {}", x);
    }
}

gives this error:

error[E0597]: `data` would be dropped while still borrowed
 --> src/main.rs:4:5
   |
 4 |     data.iter().cloned()
   |     ^^^^ borrowed value does not live long enough
 5 | }
   | - borrowed value only lives until here
   |
   = note: borrowed value must be valid for the static lifetime...

I think we could do better. For example, we don't explain anything about how impl Iterator disallows lifetimes; and I think we can clarify why `data is being dropped.

I don't yet have a concrete suggestion, though, have to think about it.

Related to #52534 -- in some sense a specific instance of that.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.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