2

In Rust, this code compiles and runs but generates no error or output:

fn main() {
    for number in 4..1 {
        println!("{}!", number);
    }
}

Shouldn't Rust consider this as invalid code and not compile or give a warning since it also doesn't seem to understand that I want to iterate in reverse?

This code generates no Assembly output.

lijeles952
  • 265
  • 1
  • 8
  • Does this answer your question? [Range where start > end](https://stackoverflow.com/questions/70329833/range-where-start-end) – joshmeranda Jun 03 '22 at 14:54
  • I think he asked for an explanation instead of a fix – Finomnis Jun 03 '22 at 14:55
  • For what it is worth, `cargo clippy` warns about that with a [`reversed_empty_ranges`](https://rust-lang.github.io/rust-clippy/master/index.html#reversed_empty_ranges) and suggests writing `(1..4).rev()` instead. – rodrigo Jun 03 '22 at 15:04

1 Answers1

5

Let's see what happens internally.

4..1

is actually just syntactical sugar for

std::ops::Range { start: 4, end: 1 }

Which is defined as:

The range start..end contains all values with start <= x < end. It is empty if start >= end.

Therefore, as specified in the documentation, for 4..1 should do nothing, as it always iterates forwards and the start is already past the end.

To iterate backwards, use:

(1..4).rev()
Finomnis
  • 18,094
  • 1
  • 20
  • 27
  • It might be slightly unintuitive to the original poster that `(1..4).rev()` _does not_ result in the range `[4, 3, 2]`. Do you think it should be clarified in your answer? – Vincent Savard Jun 03 '22 at 15:02
  • 2
    @VincentSavard Might be. Unsure what to do about that. Tbh I think it's quite self-explanatory if you look at the definition of `Range`. – Finomnis Jun 03 '22 at 15:03