Home > Enterprise >  rust for loop with floating point types?
rust for loop with floating point types?

Time:08-16

In c I very often do this kind of looping:

for(float t=0; t < threshold; t  = step_size)
{}

I am trying to replicate it in rust. I could of course use a while loop, but for loops with the above syntax have a couple of things I like:

  1. You can immediately tell how the loop should behave in one line (as opposed to 3)
  2. While loops force the update statement to be at the bottom, if your while is large that makes it harder to find the update statement if you need to tweak it.
  3. All metavariables associated with the loop exist only within the scope of the loop.

Can you replicate this in rust?

CodePudding user response:

Because you "very often do this", I'm going to assume that you're well aware of all the edge cases, unexpected results, and footguns this entails, while mentioning this answer which outlines a nice alternative.

While there isn't syntax for this in Rust, you can use one of the handy iterator utilities the standard library provides, in this case the successors function, which yields a value based on its predecessor, seems like a good fit. You can define a function that returns an iterator just like you want that you can use in a for loop:

fn float_loop(start: f64, threshold: f64, step_size: f64) -> impl Iterator<Item = f64> {
    std::iter::successors(Some(start), move |&prev| {
        let next = prev   step_size;
        (next < threshold).then_some(next)
    })
}

fn main() {
    for t in float_loop(0.0, 1.0, 0.1) {
        println!("{}", t);
    }
}

This will print

0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
  • Related