Skip to content

Iterator::sum requires type annotations in seemingly simple cases #100802

@glandium

Description

@glandium

Even with type annotations, Iterator::sum is not handled very nicely:

    let foo: usize = (1usize..10).sum() + 1usize;

fails to build with:

error[[E0283]](https://doc.rust-lang.org/stable/error-index.html#E0283): type annotations needed
 --> src/main.rs:2:35
  |
2 |     let foo: usize = (1usize..10).sum() + 1usize;
  |                                   ^^^ cannot infer type of the type parameter `S` declared on the associated function `sum`
  |
  = note: cannot satisfy `_: Sum<usize>`
note: required by a bound in `std::iter::Iterator::sum`
help: consider specifying the generic argument
  |
2 |     let foo: usize = (1usize..10).sum::<S>() + 1usize;
  |                                      +++++
help: consider specifying the type argument in the function call
  |
2 |     let foo: usize = (1usize..10).sum::<S>() + 1usize;
  |                                      +++++

The converse:

    let bar: usize = 1usize + (1usize..10).sum();

fails to build with:

error[[E0284]](https://doc.rust-lang.org/stable/error-index.html#E0284): type annotations needed: cannot satisfy `<usize as Add<_>>::Output == usize`
 --> src/main.rs:2:29
  |
2 |     let bar: usize = 1usize + (1usize..10).sum();
  |                             ^ cannot satisfy `<usize as Add<_>>::Output == usize`

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.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