Consider the program:
fn main() {
let mut nums = vec![1, 3];
let mut counter = 0;
for mut p in nums.into_iter().cycle() {
println!("{}", p);
p += 1;
if p > 10 {
break;
}
counter += 1;
if counter > 1000 {
println!("ERROR");
break;
}
}
}
I expected this to print 1, 3, 2, 4, 3, 5, ... until it got to 10 and then halt. Instead, I got a warning:
warning: variable does not need to be mutable
--> src/main.rs:2:9
|
2 | let mut nums = vec![1, 2, 3];
| ----^^^^
| |
| help: remove this `mut`
|
And then an infinite loop (well, only finite because I added the counter
in there). Why is this an infinite loop?
The behavior I wanted can also be written this way:
for idx in (0..nums.len()).cycle() {
let p = &mut nums[idx];
println!("{}", p);
*p += 1;
if *p > 10 {
break;
}
}
That works - but I don't want to iterate over the indices, I want to directly iterate over the values. Is there a way to write what I want?