kdwarn

Codeberg Mastodon Feeds

Home > Programming > Blog > Looping with modulus

Looping with modulus

July 27, 2022

daybook, rust, embedded | permalink

You can use a modulus operator to loop around the end of a range quite efficiently, which would come in handy in an infinite loop. I discovered this in Section 5.6 of the embedded Rust Discovery book. It was used there for turning LEDs on and off; here is just printing out the vars:

fn main() {
    let end = 10;
    loop {
        for curr in 0..end {
            // Use modulus in defining next, to wrap around end of range.
            let next = (curr + 1) % end;
            dbg!(curr);
            dbg!(next);
        }
        std::thread::sleep(std::time::Duration::new(3, 0))
    }
}