[Solved] Changing index while iterating

I am currently porting some c++ code to Rust. That code used ancient C for loops as expected. If I simplify that for-loop, it boils down to this:

for(int cur = 0; cur < 11; ++cur){
      std::cout << cur << std::endl;
      if(cur == 4) {
          // Change the index
          cur = 8;
      }
}

To say exactly, that code needs to change cur while iteration. That example code outputs:

0
1
2
3
4
9
10

I am a novice in Rust so I coded it as:

for mut cur in 0..11 {
        println!("{:?}", cur);
        if cur == 4 {
            cur = 8;
        }
    }

and it doesn’t work:

0
1
2
3
4
5
6
7
8
9
10

Sorry for asking this dumb question. Any kind of help or tip will be well appreciated!

Thanks!

You’d need to do a while loop instead.

1 Like

Thanks for the quick answer! So there is no way other than a while loop, is it?

So equivalent code using while loop would be:

let mut cur = 0;
while cur < 11 {
println!("{}", cur);
   if cur == 4 {
      cur = 8;
   }
   cur += 1;
}

Thanks!

1 Like

Yeah, the iteration is controlled by the iterator; you can’t modify the variable to control it.

1 Like

wow this is really cool. After looking at the disassembly I saw that the compiler just packs all this stuff in one loop

1 Like