As of Rust 1.1
You can always write this old fashionedly:
fn main() { let mut i = 0; while i < 100 { println!("i: {}", i); i += 2; } }
What can then be abstracted:
use std::ops::Add; fn step_by<T, F>(start: T, end_exclusive: T, step: T, mut body: F) where T: Add<Output = T> + PartialOrd + Copy, F: FnMut(T) { let mut i = start; while i < end_exclusive { body(i); i = i + step; } } fn main() { step_by(0, 100, 2, |i| { println!("i: {}", i); }) }
An interesting historical note, I believe that initially the whole cycle was done with a closure like this before iterators became extremely common.
Shepmaster
source share