Skip to content

Confusing error message when collecting an iterator of results into a single result #60440

Closed

Description

The code:

struct ErrorThing;

fn main() {
    let input = vec![Ok(4_i32), Err(ErrorThing), Err(ErrorThing)];
    let res: Result<i32, ErrorThing> = input.into_iter().collect();
}

Produces this error:

error[E0277]: a collection of type `i32` cannot be built from an iterator over elements of type `i32`
 --> src/main.rs:6:58
  |
6 |     let res: Result<i32, ErrorThing> = input.into_iter().collect();
  |                                                          ^^^^^^^ a collection of type `i32` cannot be built from `std::iter::Iterator<Item=i32>`
  |
  = help: the trait `std::iter::FromIterator<i32>` is not implemented for `i32`
  = note: required because of the requirements on the impl of `std::iter::FromIterator<std::result::Result<i32, ErrorThing>>` for `std::result::Result<i32, ErrorThing>`

error: aborting due to previous error

The message sounds very strange because a collection with elements of type i32 certainly can be built from an iterator over elements of type i32. The real problem is that a value of type i32 cannot be unambiguously built from an iterator over elements of type i32, because a folding function would need to be provided for it to make sense.

In cases where you are trying to collect into a non-collection type, the message should use a different word, probably "value".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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.F-on_unimplementedError messages that can be tackled with `#[rustc_on_unimplemented]`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