Reputation: 9622
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:
Can you replicate this in rust?
Upvotes: 0
Views: 664
Reputation: 6651
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
Upvotes: 4