0

Rust for loop countdown using range operator does not work When I try this

for i in 1..9 {println!("{}",i)}

I got

1
2
3
4
5
6
7
8

Which is to be expected But when I try this

 for i in 9..1 {println!("{}",i)}

I got nothing

I'm expecting to see something like this

8
7
6
5
4
3
2
1

Question

  1. Why does it not work
  2. How to count down using for loop in Rust
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
Kyrielight
  • 119
  • 5
  • `i in (1..9).rev()` – Dogbert Jun 27 '22 at 08:59
  • Yes. But not very satisfying. Why does it design this way? – Kyrielight Jun 27 '22 at 09:05
  • Changing it now is a breaking change anyway, so impossible. But I guess perf considerations. – Chayim Friedman Jun 27 '22 at 09:06
  • 2
    @Kyrielight it was designed this way because when the starting and end points are variables, not literals, it's more easy to think that if the end is smaller than the beginning, it won't do anything, rather than suddenly going the other way around. This greatly simplifies many things. For instance, if you wanted to insert a range in a segment tree, you would expect to insert the empty interval if you inserted 1..0, not to insert a backward-going (whatever that could mean) interval. Besides, making it going the other direction is quite easy. – jthulhu Jun 27 '22 at 10:21
  • @Kyrielight makes sense I guess, but this should really be a compiler warning in this specific context. Or I guess more generally loops whose repetition count eagerly evaluates to zero should be. There are more than one ways to mess this up with an iterator in a really misleading way. – Lőrinc Bethlenfalvy Jul 06 '22 at 16:57
  • 1
    @LőrincBethlenfalvy [`clippy::reversed_empty_ranges`](https://rust-lang.github.io/rust-clippy/master/index.html#reversed_empty_ranges). – Chayim Friedman Jul 07 '22 at 07:57

0 Answers0