7

I need to write a loop in Rust that runs its body from a value down to and including n = 0. At first, I wrote it like this:

for n in max..0 {
    // ...
}

However, it just runs until n = 1.

The best alternative I can think of is this:

let mut n = max;
loop {
    // ...

    if n == 0 {
        break;
    }
    n -= 1;
}

This solution is really clumsy and doesn't satisfy me. Is there a better way of writing that loop, e.g. a for-loop with a range including the right boundary value of the ..?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
David
  • 1,672
  • 2
  • 13
  • 32

0 Answers0