Skip to content

Detect when user tries to write Iterator that incorrectly borrows from Self and would need GATs #125337

Closed
@estebank

Description

@estebank

Code

struct Data {
    v: Vec<i32>,
}

impl Iterator for Data {
    type Item = &[i32];
    fn next(&mut self) -> Option<Self::Item> {
        let mut a = 0;
        let mut b = 0;
        Some(&self.v[a..b])
    }
}

fn main() {}

Current output

error[E0637]: `&` without an explicit lifetime name cannot be used here
 --> src/main.rs:6:17
  |
6 |     type Item = &[i32];
  |                 ^ explicit lifetime name needed here

Desired output

error[E0637]: `&` without an explicit lifetime name cannot be used here
 --> src/main.rs:6:17
  |
6 |     type Item = &[i32];
  |                 ^ explicit lifetime name needed here
note: associated type `Iterator::Item` is declared without lifetime parameters, so using a borrowed type for them requires that lifetime to come from the implemented type, so `Data` should be declared with a lifetime
note: you can't create an `Iterator` that borrows each `Item` from itself, as it doesn't use Generic Associated Types, but you can instead create a new type that borrows `Data` and implement `Iterator` for that type: <LINK TO EXAMPLE>

Rationale and extra context

No response

Other cases

No response

Rust Version

1.78.0

Anything else?

Taken from https://users.rust-lang.org/t/lifetime-error-from-iterator-with-its-item-as-a-reference/108863

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-iteratorsArea: IteratorsA-lifetimesArea: Lifetimes / regionsD-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.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