Rayon for Rust: A Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is Rayon and why is it needed?



Rayon is a powerful library for the Rust programming language that provides a simple and safe way to parallelize computations. Its main feature is the concept of parallel iterators. Instead of manually managing threads, mutexes, and channels, you simply replace a sequential iterator (`.iter()`) with a parallel one (`.par_iter()`), and Rayon automatically distributes the work across all available CPU cores.



Why is this library needed? In the modern world, multi-core processors have become the standard. However, writing multi-threaded code manually is a complex task, fraught with data races, deadlocks, and other hard-to-find errors. Rayon takes on all these complexities, providing:

  • Automatic work distribution: The library itself decides how to split data into parts and distribute them among threads.
  • Type-level safety: Thanks to Rust's ownership and borrowing system, Rayon guarantees the absence of data races at compile time.
  • Work-stealing: If one thread finishes its task earlier than others, it "steals" work from busy threads, ensuring even load across all cores.
  • Ease of use: The Rayon API is intuitive for any developer familiar with Rust iterators.


Rayon is ideal for tasks that require processing large volumes of data: image processing, simulations, numerical calculations, file parsing, and much more. If your task can be easily broken down into independent subtasks (data parallelism), Rayon is your choice.



Installation



Rayon is installed in the standard way for Rust — via the Cargo package manager. Add the following line to the Cargo.toml file of your project:



[dependencies]rayon = "1.10"


After that, run the command cargo build, and Cargo will automatically download and compile the library. Rayon is a "pure" Rust library, so no additional dependencies or system requirements are needed. It works on Windows, macOS, and Linux.



Quick Start



Let's start with a classic example: summing a large array of numbers. First, we'll do it sequentially, and then in parallel using Rayon.



// Import the libraryuse rayon::prelude::*;

fn main() { // Create a large vector of numbers let numbers: Vec<u64> = (1..=10_000_000).collect();

// --- Sequential summation --- let sequential_start = std::time::Instant::now(); let sum_sequential: u64 = numbers.iter().sum(); let sequential_duration = sequential_start.elapsed(); println!("Sequential sum: {} (time: {:?})", sum_sequential, sequential_duration);

// --- Parallel summation using Rayon --- let parallel_start = std::time::Instant::now(); let sum_parallel: u64 = numbers.par_iter().sum(); // Replaced .iter() with .par_iter() let parallel_duration = parallel_start.elapsed(); println!("Parallel sum: {} (time: {:?})", sum_parallel, parallel_duration);

// Speedup comparison println!("Speedup: {:.2}x", sequential_duration.as_secs_f64() / parallel_duration.as_secs_f64());}


In this example, we made just one change: we replaced .iter() with .par_iter(). Rayon automatically split the vector into parts, distributed them across threads, computed partial sums, and then combined the results. On a multi-core processor, you will see a significant speedup.



Main Methods/Functions



1. par_iter()

What it does: Creates a parallel iterator from references to elements of a collection. This is the most

Recommendations