Noob confused about "0..5" vs. "5..0" iterating?

When I try learning a new language, I follow a tutorial, and along the way TRY some modifications to see "what happens"

This snippet works fine:
fn main() {
for i in 0..5 {
println!("Flappy {}", i);
for j in 0..5 {
println!(" Floopy {}", j);
}
}
}

But when I changed the 'Floopy' section to "for j in 5..0 {"
all I get are 5 'Flappy' lines.

I can't find where "0..5" versus "5..0" is discussed in any documentation...

Help?

I can't find it documented anywhere either, but the situation is that ranges are always increasing. To iterate from 5 down to 1 use (1..=5).rev() which reverses the order of the iterator.

(I changed the category of this topic to Help. The Tutorial category is for announcing or discussing published tutorials.)

6 Likes

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

7 Likes

P.s. Check out pinned code formatting guide.

There's reversed empty ranges clippy lint. Maybe it could be included in rustc by default?

3 Likes