Hi all!
I recently had a use case for cycling over the letters A to Z for a project. From what I found so far this is usually done with a modulo-based approach which I did like this:
let mut counter: u8 = 0;
for line in parse_lines() {
match line {
foo => counter += 1,
bar => {
let chain_id = std::str::from_utf8(&[65 + (chain_counter % 26)])
.expect("Parsing failed").to_string();
// do stuff with chain_id
}
}
}
Although I already kept it quite simple this seems less legible to me than an approach based on an iterator:
let mut iter = ('A'..='Z').cycle();
// Initialize first value
iter.next();
for line in parse_lines() {
match line {
foo => iter.next(),
bar => {
let chain_id = iter.unwrap().to_string();
// do stuff with chain_id
}
}
}
In my context the loop is run through a lot and the above code would be executed many times. I'm thinking the exact approach doesn't matter too much here since both seem to work and, as far as I can see, no unnecessary allocations should happen either way.
Is there something obvious I'm missing here?