Skip to content

Confusing "expected reference, found ..." error when trying to chain Iterator<T> and Iterator<&T> #68095

@jstasiak

Description

@jstasiak

I'm running rustc 1.40.0.

The code:

fn main() {
    let a = (0..3).chain([3, 4, 5].iter());
}

Trying to compile it results in:

% rustc test1.rs           
error[E0271]: type mismatch resolving `<std::slice::Iter<'_, {integer}> as std::iter::IntoIterator>::Item == {integer}`
 --> test1.rs:2:20
  |
2 |     let a = (0..3).chain([3, 4, 5].iter());
  |                    ^^^^^ expected reference, found integer
  |
  = note: expected type `&{integer}`
             found type `{integer}`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0271`.

If one focues one the ^^^^^ expected reference, found integer line (as I did) one is faced with the following difficulties:

  1. It's the chain identifier that's underlined/pointed towards here which is (to me) confusing
  2. If I follow the "expected reference, found integer" advice naively and without trying to get to the bottom of things I may think "ok, the problem is with the chain call, it expects references but I give it integers, let's add references" and produce the following:
fn main() {
    let a = (0..3).chain([&3, &4, &5].iter());
}

And the error gets even more confusing:

% rustc test2.rs       
error[E0271]: type mismatch resolving `<std::slice::Iter<'_, &{integer}> as std::iter::IntoIterator>::Item == {integer}`
 --> test2.rs:2:20
  |
2 |     let a = (0..3).chain([&3, &4, &5].iter());
  |                    ^^^^^ expected reference, found integer
  |
  = note: expected type `&&{integer}`
             found type `{integer}`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0271`.

That attempt to fix things was of course totally incorrect, but the error messages don't help here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-iteratorsArea: IteratorsC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.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