Skip to content

Misleading error message with negative range #83413

@vultix

Description

@vultix

Given the following code: Playground

fn main() {
  for x in -5..5 {
      do_something(x);
  }    
}

fn do_something(val: usize) {}

The current output is:

error[E0277]: the trait bound `usize: Neg` is not satisfied
 --> src/main.rs:2:12
  |
2 |   for x in -5..5 {
  |            ^^ the trait `Neg` is not implemented for `usize`

error: aborting due to previous error

This created confusion for a new Rust user on our team.

Ideally the range type would be inferred to be i32:

error[E0308]: mismatched types
 --> src/main.rs:3:20
  |
3 |       do_something(x);
  |                    ^ expected `usize`, found `i32`
  |
help: you can convert an `i32` to a `usize` and panic if the converted value doesn't fit
  |
3 |       do_something(x.try_into().unwrap());
  |                    ^^^^^^^^^^^^^^^^^^^^^

Alternatively the output could mention why the type was inferred to be usize:

  |
2 |   for x in -5..5 {
  |            ^^ the trait `Neg` is not implemented for `usize`
  |
help: type `usize` was inferred due to call on line 3
  |
3 |      do_something(x);
  |                   ^

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-inferenceArea: Type inferenceA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.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