How should I go if I want to iterate with a custom step in stable Rust? Essentially something like the C/C++
for (in
You can use the iterator_step_by
feature.
Here is an example of two threads running, one of them printing out odd numbers and the other even ones:
#![feature(iterator_step_by)]
extern crate thebook;
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in (1..1000).step_by(2) {
println!("{}", i);
}
});
for i in (2..1000).step_by(2) {
println!("{}", i);
}
handle.join();
}
Without this feature, you can also use a filter on the range:
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in (1..1000).filter(|x| x % 2 != 0) {
println!("{}", i);
}
});
for i in (2..1000).filter(|x| x % 2 == 0) {
println!("{}", i);
}
handle.join();
}