[Solved] Changing index while iterating


#1

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!


#2

You’d need to do a while loop instead.


#3

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!


#4

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


#5

I am not sure if it could help you but I try a bit different solution:

(0..11).filter(|x| {
    match x {
        &4...7 => false,
         _ => true,
    }
}).for_each(|x| println!("{}", x))

#6

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