What is a stable way to iterate on a range with custom step?

前端 未结 6 903
不思量自难忘°
不思量自难忘° 2021-01-01 18:41

How should I go if I want to iterate with a custom step in stable Rust? Essentially something like the C/C++

for (in         


        
6条回答
  •  鱼传尺愫
    2021-01-01 19:27

    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();
    }
    

提交回复
热议问题