Skip to content

unclear diagnostic with invalid suggestion for lifetime error involving an opaque type #80150

Closed
@ben0x539

Description

@ben0x539

This code is invalid because it returns a reference to a local:

fn foo<T: 'static>() -> Option<impl Iterator<Item = T>> {
    let mut n = None.into_iter();
    let i: &mut dyn Iterator<Item=T> = &mut n;
    Some(i)
}

It produces this diagnostic:

error[E0597]: `n` does not live long enough
 --> src/lib.rs:3:40
  |
1 | fn foo<T: 'static>() -> Option<impl Iterator<Item=T>> {
  |                         ----------------------------- opaque type requires that `n` is borrowed for `'static`
2 |     let mut n = None.into_iter();
3 |     let i: &mut dyn Iterator<Item=T> = &mut n;
  |                                        ^^^^^^ borrowed value does not live long enough
4 |     Some(i)
5 | }
  | - `n` dropped here while still borrowed
  |
help: you can add a bound to the opaque type to make it last less than `'static` and match `'static`
  |
1 | fn foo<T: 'static>() -> Option<impl Iterator<Item=T>> + 'static {
  |                                                       ^^^^^^^^^
  1. I don't understand what "help: you can add a bound to the opaque type to make it last less than 'static and match 'static" means
  2. The suggestion(?) of Option<impl Iterator<Item=T>> + 'static isn't valid

It's probably trying to say Option<impl Iterator<Item=T> + 'static>, if we try that, we get a more straightforward error message.

I'm not sure if this is just #69982, but that one seems to want a closure-specific other diagnostic rather than being generally confused like me.

(tried this on playground with stable 1.48 and nightly)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-impl-traitArea: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch.A-lifetimesArea: Lifetimes / regionsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-bugCategory: This is a bug.D-confusingDiagnostics: Confusing error or lint that should be reworked.D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.P-mediumMedium priorityT-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