6

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.

1
  • 2
    There is no issue. The value i is not an index, its a value from the range you generated with 2..points.len(). You can change and modify i as much as you want, it will just be reassigned for the next iteration. If you tried to take a value from points with points[i] you may get an index error, but just modifying it on its own is no issue (as long as you don't exceed the type limits) Commented Dec 8, 2021 at 23:34

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

Comments

1

In your case, I'd use a while loop:

fn main(){
    let mut i = 0;
    while i < 10 {
        println!("i = {}", i);
        if i == 5 {
            i = i + 2;
            continue
        }
        i = i + 1;
    }
}

Playground

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.