WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Advanced · question 55 of 100

How do you use the rayon crate for parallelism in Rust? Provide a practical example.?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

Rayon is a crate that provides a high-level interface for parallelism in Rust. It allows developers to write parallel code without having to worry about the low-level details of threading and synchronization.

To use Rayon for parallelism in Rust, the ‘rayon‘ crate must first be added as a dependency in the ‘Cargo.toml‘ file. Here is an example:

    [dependencies]
    rayon = "1.5"

Once it has been added as a dependency, the ‘rayon::iter::ParallelIterator‘ trait can be used to parallelize iterators. Let’s consider the following code that calculates the sum of square roots of numbers in a vector using a serial (non-parallel) approach:

    fn main() {
        let nums = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let sum = nums.iter().map(|x| x.sqrt()).sum::<f64>();
        println!("Sum of square roots: {}", sum);
    }

Using Rayon’s parallel iterators, we can parallelize the computation of the sum, thereby potentially speeding up the computation on multi-core processors. Heres how to do it:

    use rayon::prelude::*;
    
    fn main() {
        let nums = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let sum = nums.par_iter().map(|x| x.sqrt()).sum::<f64>();
        println!("Sum of square roots: {}", sum);
    }

In this example, ‘nums.par_iter()‘ is used instead of ‘nums.iter()‘ to create a parallel iterator, and the ‘sum()‘ is called on the parallel iterator. The rest of the code is the same as before.

Rayon uses a work-stealing algorithm to dynamically distribute the workload across the available cores to optimize performance. By using parallel iterators, developers can easily and safely parallelize their code without having to worry about the complexity of low-level threading and synchronization.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics