For loops and ownership

You do need a mutable reference and yes it does modify the range itself (range implements iterator and iterating over a range consumes the range).

You can do:

let mut r = 1..4;
for i in &mut r {
    println!("{}", i);
}
for i in &mut r {
    println!("{}", i);
}

or

let mut r = 1..4;
for i in r.by_ref() {
    println!("{}", i);
}
for i in r.by_ref() {
    println!("{}", i);
}

but this is kind of pointless because the second loop will never run.

3 Likes