How to do it...

  1. Create a Rust project to work on during this chapter with cargo new chapter-seven.
  2. Navigate into the newly-created chapter-seven folder. For the rest of this chapter, we will assume that your command line is currently in this directory.
  3. Open the Cargo.toml file that has been generated for you.
  4. Under [dependencies], add the following line:
rayon = "1.0.0"

If you want, you can go to rayon's crates.io page (https://crates.io/crates/rayon) to check for the newest version and use that one instead.

  1. Inside the src folder, create a new folder called bin.
  2. Delete the generated lib.rs file, as we are not creating a library.
  3. In the src/bin folder, create a file called par_iter.rs.
  4. Add the following code and run it with cargo run --bin par_iter:
1  extern crate rayon;
2 use rayon::prelude::*;
3
4 fn main() {
5 let legend = "Did you ever hear the tragedy of Darth Plagueis
The Wise?";
6 let words: Vec<_> = legend.split_whitespace().collect();
7
8 // The following will execute in parallel,
9 // so the exact order of execution is not foreseeable
10 words.par_iter().for_each(|val| println!("{}", val));
11
12 // par_iter can do everything that a normal iterator does, but
13 // in parallel. This way you can easily parallelize any
algorithm
14 let words_with_a: Vec<_> = words
15 .par_iter()
16 .filter(|val| val.find('a').is_some())
17 .collect();
18
19 println!(
20 "The following words contain the letter 'a': {:?}",
21 words_with_a
22 );
23 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.81.33