Skip to content

Diagnostics for an immutable reference to an iterator #64068

Closed
@kornelski

Description

@kornelski

This problem comes up in generic contexts, but the simplest code to reproduce is:

let iter = &[1,2,3].iter();
for i in iter {
}

Results in:

error[E0277]: &std::slice::Iter<'_, {integer}> is not an iterator

 | for i in iter {
 |          ^^^^ `&std::slice::Iter<'_, {integer}>` is not an iterator
 |

= help: the trait std::iter::Iterator is not implemented for &std::slice::Iter<'_, {integer}>
= note: required by std::iter::IntoIterator::into_iter

At first glance it looks wrong, because it says that Iter is not an iterator. It is not obvious that immutability of the shared reference is what breaks the code.

Interestingly, an only a slightly different code produces a better suggestion:

let iter = [1,2,3].iter();
for i in &iter {
}

help: consider removing 1 leading &-references

So possibly the condition for the help text is too narrow, and could be extended to work in general case. It could also suggest using &mut as another alternative.

(#37914 has a similar problem, but a different root cause)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-iteratorsArea: IteratorsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.D-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