Skip to content

Suggest valid reverse for loop if an invalid variant is used #100635

Open
@Rageking8

Description

@Rageking8

Given the following code: link

fn main() {
    for i in 10..0 {
        println!("{i}");
    }
    
    for i in (10..0).rev() {
        println!("{i}");
    }
    
    for i in (10..0).step_by(-1) {
        println!("{i}");
    }
}

The current output is:

Compiling playground v0.0.1 (/playground)
error[[E0600]](https://doc.rust-lang.org/nightly/error-index.html#E0600): cannot apply unary operator `-` to type `usize`
  --> src/main.rs:10:30
   |
10 |     for i in (10..0).step_by(-1) {
   |                              ^^
   |                              |
   |                              cannot apply unary operator `-`
   |                              help: you may have meant the maximum value of `usize`: `usize::MAX`
   |
   = note: unsigned values cannot be negated

For more information about this error, try `rustc --explain E0600`.
error: could not compile `playground` due to previous error

Ideally the compiler should check if the range's start >= end and inform the user that its an empty iterator.

Then for the above few incorrect variants (and possibly more), suggest the correct way to write a reverse for loop.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-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