I'm looking at some code that looks like this:
for mut i in 2..points.len() {
// Do something
if some_condition {
i = 1;
}
}
It compiles and runs fine (it seems). My first intuition was that it would be better as a while
loop.
Then I started wondering, is this something that's legal to do in Rust in general?
What happens if you happen to increment i
beyond the range? I'm guessing trouble obviously...
I'd like to know if there are any kind of issues modifying the index while going through the range with it. I'm assuming that the i
stays in range, but I would be interested to know what happens when it goes beyond the range too.
CodePudding user response:
Your code
for mut i in 2..points.len() {
// Do something
if some_condition {
i = 1;
}
}
will internally in the compiler be rewritten in simpler terms using loop
, into something like this:
let mut iter = (2..points.len()).into_iter();
loop {
if let Some(mut i) = iter.next() {
// Do something
if some_condition {
i = 1;
}
} else {
break
}
}
In this form, it should hopefully be more clear what actually happens here: i
is declared inside of the loop body, and assigned the next value from the range iterator at the beginning of each iteration. If you modify it, it will just be reassigned on the next iteration. Specifically, you can't change i
to affect anything outside of the current iteration of the loop.