In Rust, how does one do variable sized steps in a for
style loop? I'm able to do fixed sized steps with this construct:
for i in (0..vals.len()).step_by(4)
{
println!("{}: {}", i, vals[i]);
}
or the more proper:
for (i,val) in vals.iter().enumerate().step_by(4)
{
println!("{}: {}", i, val);
}
but what I'd really like to do is something like:
for i in 0..vals.len()
{
println!("{}: {}", i, vals[i]);
if vals[i] == 1 { i += 2; }
else if vals[i] == 2 { i += 4; }
}
but of course, modifying i
doesn't affect the loop iterator.
Coming from a primarily C background, the reliance on iterators in modern languages often feels like programming with mitts on. Usually Google comes to the rescue, but I haven't found any solution to what seems like a fairly simple problem.
The best I've come up with is
let mut i:usize = 0;
while i < vals.len()
{
println!("{}: {}", i, vals[i]);
if vals[i] == 1 { i += 2; }
else if vals[i] == 2 { i += 4; }
}
but that feels like a poor man's for
loop and contrary to what I should be doing to take advantage of an iterator-equipped language. Is there a variant of continue
that skips iterations, or a way to call skip
on the iterator from within the loop?