Skip to content
Tutorials Center
My learning

Topics

Lesson 130 of 132 ยท Practice and Review

Practice Problems: Traits, Iterators and Concurrency

15 harder Rust practice problems with hints and verified solutions: traits, generics, operators, iterators, closures, errors, lifetimes, Rc, threads and channels.

The fundamentals problems trained loops, strings, ownership and Option. This page is the next step: the features that make Rust feel like Rust. You will write traits and generic functions, overload operators, build iterator chains and a custom iterator, store closures, design an error type, write a struct that borrows, share data with Rc<RefCell<T>> and finally put work on several threads.

The format is the same. Each problem has a task, an editor with starter code that compiles and runs as given, a hint and a hidden solution. The comments in main show the expected output. Replace the stubs, run, and compare. Many of the problems have more than one good answer; the hint nudges you in one direction and the explanation under each solution says why we chose it.

A few habits will help:

  • Start from the types. In Rust the signature tells you most of what the body must do. Say aloud what each parameter owns or borrows before you write a line of code.
  • Let the compiler guide you. If you get a borrow-checker error, read it before changing anything; Reading Compiler Errors lists the common ones.
  • Prefer iterators to index loops when you can, but not at any price: a plain for loop is fine when it reads better.
  • Concurrency output must be deterministic. Threads run in an unpredictable order, so the concurrent problems here return values, and the tests join the threads or sort the results before printing.

Keep the cheat sheet handy.

Traits and generics

These practice traits, generics, trait bounds, Display and From and operator overloading.

1. Animals and a default method (Easy)

Implement Animal for Dog and Cat. name and sound are required; speak has a default implementation that builds the sentence "<name> says <sound>", so you write it once in the trait.

Rust Problem 1: Animals and a default method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

Inside the default method you may call the other trait methods through self: format!("{} says {}", self.name(), self.sound()). In the impls, self.name.clone() gives the dog's name and String::from("woof") its sound.

Show solution
Rust
trait Animal {
    fn name(&self) -> String;
    fn sound(&self) -> String;

    fn speak(&self) -> String {
        format!("{} says {}", self.name(), self.sound())
    }
}

struct Dog {
    name: String,
}

struct Cat {
    name: String,
}

impl Animal for Dog {
    fn name(&self) -> String {
        self.name.clone()
    }
    fn sound(&self) -> String {
        String::from("woof")
    }
}

impl Animal for Cat {
    fn name(&self) -> String {
        self.name.clone()
    }
    fn sound(&self) -> String {
        String::from("meow")
    }
}

fn main() {
    let animals: Vec<Box<dyn Animal>> = vec![
        Box::new(Dog { name: String::from("Rex") }),
        Box::new(Cat { name: String::from("Tom") }),
    ];
    for animal in &animals {
        println!("{}", animal.speak());
    }
}

The default method lives in one place yet works for every implementor. Box<dyn Animal> allows one vector to hold different types; each call goes through a vtable (dynamic dispatch). Returning &str from name would avoid the clone, but then the signature would need a lifetime tied to &self. See Trait Objects.

2. A generic largest (Easy)

Write largest for slices of any type that can be compared and copied. It returns None for an empty slice.

Rust Problem 2: A generic largest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

The bounds are T: PartialOrd + Copy. PartialOrd gives you >; Copy lets you return a value out of a borrowed slice. iter().copied() turns &T items into T. The ? operator also works on Option: let mut best = iter.next()?;.

Show solution
Rust
fn largest<T: PartialOrd + Copy>(items: &[T]) -> Option<T> {
    let mut iter = items.iter().copied();
    let mut best = iter.next()?;
    for item in iter {
        if item > best {
            best = item;
        }
    }
    Some(best)
}

fn main() {
    println!("{:?}", largest(&[3, 8, 2]));
    println!("{:?}", largest(&[1.5, -2.0]));
    println!("{:?}", largest(&['x', 'b']));
    println!("{:?}", largest::<i32>(&[]));
}

Floats only implement PartialOrd, not Ord, because NaN is not comparable; that is why the bound is the weaker trait. The standard library's iter().max() needs Ord and so does not accept f64. For types that are not Copy, return Option<&T> instead. See Trait Bounds.

3. Version numbers (Intermediate)

Make Version printable as 1.2.3 (Display), parseable from text (FromStr, so "1.2.3".parse::<Version>() works) and sortable by meaning (derive PartialOrd and Ord). When all is implemented, remove the comment markers around the sorting code.

Rust Problem 3: Version numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

Derived ordering compares fields in declaration order, which is exactly major, then minor, then patch. In from_str, split on '.', check the count, and write a small closure that parses one part and maps the error to your message. ? then handles each part.

Show solution
Rust
use std::fmt;
use std::str::FromStr;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct Version {
    major: u32,
    minor: u32,
    patch: u32,
}

impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
    }
}

impl FromStr for Version {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = s.split('.').collect();
        if parts.len() != 3 {
            return Err(format!("expected 3 parts, got {}", parts.len()));
        }
        let number = |part: &str| {
            part.parse::<u32>()
                .map_err(|e| format!("bad part {part:?}: {e}"))
        };
        Ok(Version {
            major: number(parts[0])?,
            minor: number(parts[1])?,
            patch: number(parts[2])?,
        })
    }
}

fn main() {
    println!("{:?}", "1.2.3".parse::<Version>());
    println!("{:?}", "1.2".parse::<Version>());
    println!("{:?}", "1.x.3".parse::<Version>());

    let mut all: Vec<Version> = ["1.10.0", "1.2.0", "1.2.10", "0.9.9"]
        .iter()
        .map(|s| s.parse().unwrap())
        .collect();
    all.sort();
    let text: Vec<String> = all.iter().map(|v| v.to_string()).collect();
    println!("{}", text.join(" < "));
}

Comparing the strings "1.10.0" and "1.2.0" would put 1.10 before 1.2, because '1' < '2'. Numbers fix that. Implementing Display gives you to_string() for free. If you reordered the struct's fields, the derived Ord would silently change, so keep the field order meaningful. See Display and From.

4. A 2D vector with operators (Intermediate)

Make Vec2 support a + b, a - b, -a, a * 3.0 and 2.0 * a. Each operator is a trait in std::ops.

Rust Problem 4: A 2D vector with operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

Each method builds a new Vec2 from the fields of self and the other operand. Vec2 is Copy, so using a twice in main is fine. The impl Mul<Vec2> for f64 is allowed even though f64 is a foreign type, because Vec2 is local (the orphan rule). Just swap the operands and reuse the first multiplication.

Show solution
Rust
use std::ops::{Add, Mul, Neg, Sub};

#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
    x: f64,
    y: f64,
}

impl Add for Vec2 {
    type Output = Vec2;
    fn add(self, other: Vec2) -> Vec2 {
        Vec2 { x: self.x + other.x, y: self.y + other.y }
    }
}

impl Sub for Vec2 {
    type Output = Vec2;
    fn sub(self, other: Vec2) -> Vec2 {
        Vec2 { x: self.x - other.x, y: self.y - other.y }
    }
}

impl Neg for Vec2 {
    type Output = Vec2;
    fn neg(self) -> Vec2 {
        Vec2 { x: -self.x, y: -self.y }
    }
}

impl Mul<f64> for Vec2 {
    type Output = Vec2;
    fn mul(self, k: f64) -> Vec2 {
        Vec2 { x: self.x * k, y: self.y * k }
    }
}

impl Mul<Vec2> for f64 {
    type Output = Vec2;
    fn mul(self, v: Vec2) -> Vec2 {
        v * self
    }
}

fn main() {
    let a = Vec2 { x: 1.0, y: 2.0 };
    let b = Vec2 { x: 3.0, y: 5.0 };
    println!("{:?}", a + b);
    println!("{:?}", b - a);
    println!("{:?}", -a);
    println!("{:?}", a * 3.0);
    println!("{:?}", 2.0 * a);
    println!("{}", a + b == Vec2 { x: 4.0, y: 7.0 });
}

The operators take self by value, which is cheap for a small Copy type. For big types you would also implement the traits for references (&a + &b). Operator overloading should keep the usual meaning: do not make + do something surprising. See Operator Overloading.

Iterators and closures

These practice iterators, iterator patterns, custom iterators, closures and sorting.

5. Top words by length (Easy)

Return the n longest words. Longer words come first; words of equal length are sorted alphabetically. The result borrows from the input, so no new strings are created.

Rust Problem 5: Top words by length

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

Copy the slice into a Vec with to_vec() (it copies references, not text), then sort_by with a comparator. Ordering has then/then_with to break ties: b.len().cmp(&a.len()).then(a.cmp(b)). Finish with truncate(n).

Show solution
Rust
fn top_by_length<'a>(words: &[&'a str], n: usize) -> Vec<&'a str> {
    let mut sorted = words.to_vec();
    sorted.sort_by(|a, b| b.len().cmp(&a.len()).then(a.cmp(b)));
    sorted.truncate(n);
    sorted
}

fn main() {
    let words = ["pear", "fig", "banana", "kiwi", "apple", "plum"];
    println!("{:?}", top_by_length(&words, 3));
    println!("{:?}", top_by_length(&words, 10).len());
    println!("{:?}", top_by_length(&[], 2));
}

Swapping a and b in the first comparison reverses the order for lengths only. The explicit lifetime 'a connects the returned slices to the text the words point to, not to the temporary slice of references. sort_by_key(|w| (Reverse(w.len()), *w)) is an equivalent one-liner.

6. Run-length encoding (Intermediate)

Compress repeated characters: "aaabccdd" becomes "3a1b2c2d". Also write decode. Assume the original text contains no digits.

Rust Problem 6: Run-length encoding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

For encode, take text.chars().peekable(); for each character count how many following characters are equal with next_if_eq(&c) in a loop. For decode, walk through the characters: a digit extends the current count (count * 10 + digit, so 12z works) and any other character is repeated count times (std::iter::repeat_n, Rust 1.82), then the count resets.

Show solution
Rust
use std::iter::repeat_n;

fn encode(text: &str) -> String {
    let mut out = String::new();
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        let mut count = 1;
        while chars.next_if_eq(&c).is_some() {
            count += 1;
        }
        out.push_str(&format!("{count}{c}"));
    }
    out
}

fn decode(text: &str) -> String {
    let mut out = String::new();
    let mut count = 0;
    for c in text.chars() {
        if let Some(digit) = c.to_digit(10) {
            count = count * 10 + digit as usize;
        } else {
            out.extend(repeat_n(c, count));
            count = 0;
        }
    }
    out
}

fn main() {
    println!("{}", encode("aaabccdd"));
    println!("[{}]", encode(""));
    println!("{}", decode("3a1b2c2d"));
    let long = "z".repeat(12);
    println!("{}", decode(&encode(&long)) == long);
}

Peekable::next_if_eq consumes the next item only when it matches, which is exactly the "keep going while the run continues" step. The digits restriction exists because the format is ambiguous otherwise: is 11a eleven as or one 1 followed by... a real format would escape digits.

7. A Fibonacci iterator (Intermediate)

Implement Iterator for Fib so that it yields 0, 1, 1, 2, 3, 5, ... forever. Then use the standard adapters: the first ten values, the first value above 1000, and the sum of the even values below four million.

Rust Problem 7: A Fibonacci iterator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

Remember the value to return (self.current) before updating the state: the new current is the old next, and the new next is the old sum. Tuple assignment (self.current, self.next) = (self.next, self.current + self.next) does it in one line. Always return Some(...): the sequence never ends, which is why the adapters take, find and take_while matter.

Show solution
Rust
struct Fib {
    current: u64,
    next: u64,
}

impl Fib {
    fn new() -> Self {
        Fib { current: 0, next: 1 }
    }
}

impl Iterator for Fib {
    type Item = u64;

    fn next(&mut self) -> Option<u64> {
        let value = self.current;
        (self.current, self.next) = (self.next, self.current + self.next);
        Some(value)
    }
}

fn main() {
    let first_ten: Vec<u64> = Fib::new().take(10).collect();
    println!("{first_ten:?}");

    println!("{:?}", Fib::new().find(|&n| n > 1000));

    let even_sum: u64 = Fib::new()
        .take_while(|&n| n < 4_000_000)
        .filter(|n| n % 2 == 0)
        .sum();
    println!("{even_sum}");
}

Implementing next alone gives you dozens of adapters for free. The iterator is lazy and infinite, so each pipeline stops by itself: take(10), find and take_while all end early. A plain Fib::new().collect::<Vec<_>>() would never finish, and in debug builds it would panic with an overflow after about 93 terms. See Custom Iterators.

8. Closures that remember (Intermediate)

Write make_counter, which returns a closure that returns 1, 2, 3, ... on successive calls, and compose, which joins two functions into one. Both return closures, so they use impl Fn... return types.

Rust Problem 8: Closures that remember

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

For the counter, declare let mut count = 0; outside the closure and return move || { count += 1; count }. The move gives the closure its own copy, so each counter has independent state. For compose, the closure must own f and g: move |x| g(f(x)).

Show solution
Rust
fn make_counter() -> impl FnMut() -> u32 {
    let mut count = 0;
    move || {
        count += 1;
        count
    }
}

fn compose(f: impl Fn(i32) -> i32, g: impl Fn(i32) -> i32) -> impl Fn(i32) -> i32 {
    move |x| g(f(x))
}

fn main() {
    let mut a = make_counter();
    let mut b = make_counter();
    println!("{} {} {}", a(), a(), a());
    println!("{}", b());

    let add_one_then_double = compose(|x| x + 1, |x| x * 2);
    println!("{}", add_one_then_double(5));
    let double_then_add_one = compose(|x| x * 2, |x| x + 1);
    println!("{}", double_then_add_one(5));
}

The counter must be FnMut because it changes its captured state, and the caller needs let mut a. compose only reads f and g, so Fn is enough. A bonus challenge: make compose generic, fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C, so it can change types along the way. See Closures.

9. A pipeline of boxed closures (Challenge)

Build a Pipeline that stores any number of text-transforming steps and runs them in order. The steps have different closure types, so they are stored as Box<dyn Fn(&str) -> String>.

Rust Problem 9: A pipeline of boxed closures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

self.steps.push(Box::new(step)); self stores the step and returns the builder for chaining. For run, fold is perfect: start with input.to_string() and apply each step to the accumulated text: self.steps.iter().fold(input.to_string(), |text, step| step(&text)). The + 'static bound says the closure owns what it captures, which is why the second pipeline needs move.

Show solution
Rust
struct Pipeline {
    steps: Vec<Box<dyn Fn(&str) -> String>>,
}

impl Pipeline {
    fn new() -> Self {
        Pipeline { steps: Vec::new() }
    }

    fn add(mut self, step: impl Fn(&str) -> String + 'static) -> Self {
        self.steps.push(Box::new(step));
        self
    }

    fn run(&self, input: &str) -> String {
        self.steps
            .iter()
            .fold(input.to_string(), |text, step| step(&text))
    }
}

fn main() {
    let shout = Pipeline::new()
        .add(|s| s.trim().to_string())
        .add(|s| s.to_uppercase())
        .add(|s| format!("{s}!"));
    println!("{}", shout.run("  hello rust "));

    let suffix = String::from(" (checked)");
    let counter = Pipeline::new()
        .add(|s| format!("{} words", s.split_whitespace().count()))
        .add(move |s| format!("{s}{suffix}"));
    println!("{}", counter.run("a b c"));
    println!("{}", Pipeline::new().run("unchanged"));
}

Every closure has its own unnameable type, so a Vec can only hold them behind a pointer to a trait object. The cost is one heap allocation per step and a dynamic call. If all steps were the same kind, a generic parameter or plain function pointers (fn(&str) -> String) would avoid it.

Errors and lifetimes

These practice custom errors, error design and lifetimes.

10. A real error type (Intermediate)

Parse a comma-separated list of integers and add them up. Report where the problem is: an empty item, or an item that is not a number (keep the original ParseIntError as the source). Items may have spaces around them.

Rust Problem 10: A real error type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

Loop over text.split(',').enumerate() so you know the index. Trim each item; if it is empty return Err(SumError::EmptyItem(i)). Parse with item.parse::<i32>().map_err(|source| SumError::BadNumber { position: i, source })?. Positions are counted from zero. "".split(',') yields one empty item, so the empty string is reported as item 0.

Show solution
Rust
use std::fmt;
use std::num::ParseIntError;

#[derive(Debug)]
enum SumError {
    EmptyItem(usize),
    BadNumber { position: usize, source: ParseIntError },
}

impl fmt::Display for SumError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            SumError::EmptyItem(i) => write!(f, "item {i} is empty"),
            SumError::BadNumber { position, source } => {
                write!(f, "item {position} is not a number: {source}")
            }
        }
    }
}

impl std::error::Error for SumError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            SumError::BadNumber { source, .. } => Some(source),
            SumError::EmptyItem(_) => None,
        }
    }
}

fn sum_list(text: &str) -> Result<i32, SumError> {
    let mut total = 0;
    for (i, item) in text.split(',').enumerate() {
        let item = item.trim();
        if item.is_empty() {
            return Err(SumError::EmptyItem(i));
        }
        total += item
            .parse::<i32>()
            .map_err(|source| SumError::BadNumber { position: i, source })?;
    }
    Ok(total)
}

fn main() {
    for text in ["1, 2, 3", "1,,3", "4, x", ""] {
        match sum_list(text) {
            Ok(total) => println!("total = {total}"),
            Err(e) => println!("error: {e}"),
        }
    }
}

An enum error lets callers match on the cause, while Display serves people. Overriding source links the underlying error so that error reporters can print the whole chain. The thiserror crate generates all of this from attributes, but it is worth writing it once by hand. See Custom Errors.

11. A tokenizer that borrows (Challenge)

Write Tokens, a struct that holds a &str and hands out the words one at a time without allocating. The returned words must stay valid after the Tokens value is gone, which is expressed with a lifetime on the returned slice.

Rust Problem 11: A tokenizer that borrows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

Trim the leading whitespace of self.rest. If nothing is left, return None. Otherwise find the end of the word with find(char::is_whitespace) (use the full length if there is none), then split_at(end) into the word and the remainder, store the remainder back in self.rest and return the word. The signature -> Option<&'a str> (not &str) is what lets the words outlive the tokenizer.

Show solution
Rust
struct Tokens<'a> {
    rest: &'a str,
}

impl<'a> Tokens<'a> {
    fn new(text: &'a str) -> Self {
        Tokens { rest: text }
    }

    fn next_word(&mut self) -> Option<&'a str> {
        let trimmed = self.rest.trim_start();
        if trimmed.is_empty() {
            self.rest = trimmed;
            return None;
        }
        let end = trimmed.find(char::is_whitespace).unwrap_or(trimmed.len());
        let (word, rest) = trimmed.split_at(end);
        self.rest = rest;
        Some(word)
    }
}

fn collect_words(text: &str) -> Vec<&str> {
    let mut tokens = Tokens::new(text);
    let mut words = Vec::new();
    while let Some(word) = tokens.next_word() {
        words.push(word);
    }
    words
}

fn main() {
    println!("{:?}", collect_words("  hello   rust world "));
    println!("{:?}", collect_words("   "));
    println!("{:?}", collect_words("one"));
}

If next_word returned Option<&str> with the elided lifetime, the result would be tied to the &mut self borrow, and words.push(word) would conflict with the next call to next_word (E0499). Naming 'a says "this slice points into the original text, not into the tokenizer". The standard library's split_whitespace is built the same way. See Lifetimes.

Shared state and threads

These practice Rc and Arc, RefCell, threads, channels and Mutex.

12. Two services, one log (Intermediate)

Several services must append to the same log on one thread. That is shared ownership (Rc) plus mutation through a shared reference (RefCell). Write Service::new and Service::run.

Rust Problem 12: Two services, one log

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

Rc::clone(log) increments the counter and gives the service its own handle to the same vector. In run, self.log.borrow_mut().push(format!(...)) gets temporary mutable access; the borrow ends at the end of the statement. Take care never to hold a borrow() while calling borrow_mut() on the same cell: that panics at run time.

Show solution
Rust
use std::cell::RefCell;
use std::rc::Rc;

struct Service {
    name: &'static str,
    log: Rc<RefCell<Vec<String>>>,
}

impl Service {
    fn new(name: &'static str, log: &Rc<RefCell<Vec<String>>>) -> Self {
        Service { name, log: Rc::clone(log) }
    }

    fn run(&self, message: &str) {
        self.log
            .borrow_mut()
            .push(format!("[{}] {message}", self.name));
    }
}

fn main() {
    let log = Rc::new(RefCell::new(Vec::new()));
    let auth = Service::new("auth", &log);
    let db = Service::new("db", &log);

    auth.run("login");
    db.run("query");
    auth.run("logout");

    println!("owners: {}", Rc::strong_count(&log));
    for line in log.borrow().iter() {
        println!("{line}");
    }

    drop(auth);
    println!("owners: {}", Rc::strong_count(&log));
}

The three owners are log itself and the two services. run takes &self although it mutates the vector: that is interior mutability, with the borrow rules checked at run time by RefCell instead of at compile time. Rc and RefCell are not thread-safe; the next problems use their thread-safe cousins Arc and Mutex. See Rc and Arc.

13. A parallel sum (Intermediate)

Split a slice into parts chunks and sum each chunk on its own thread. Use std::thread::scope, which lets threads borrow the slice, so no cloning or Arc is needed.

Rust Problem 13: A parallel sum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

The chunk size is data.len().div_ceil(parts), but at least 1 (chunks(0) panics). Inside thread::scope(|s| { ... }), call s.spawn(move || chunk.iter().sum::<u64>()) for each chunk from data.chunks(size), collect the handles in a Vec, then join().unwrap() each and add the results.

Show solution
Rust
use std::thread;

fn parallel_sum(data: &[u64], parts: usize) -> u64 {
    let size = data.len().div_ceil(parts.max(1)).max(1);
    thread::scope(|s| {
        let handles: Vec<_> = data
            .chunks(size)
            .map(|chunk| s.spawn(move || chunk.iter().sum::<u64>()))
            .collect();
        handles.into_iter().map(|h| h.join().unwrap()).sum()
    })
}

fn main() {
    let data: Vec<u64> = (1..=1_000_000).collect();
    println!("{}", parallel_sum(&data, 4));
    println!("{}", parallel_sum(&data, 1));
    println!("{}", parallel_sum(&[], 4));
    println!("{}", parallel_sum(&data[..10], 8));
}

A scoped thread cannot outlive the scope call, so the compiler lets it borrow data. With plain thread::spawn you would get E0373 or E0597 and have to wrap the data in an Arc. Addition is associative, so the order in which chunks finish does not matter, and join gives the results back in order anyway. Summing a million numbers is too little work to benefit from threads (the spawning costs more); the pattern pays off for heavier per-item work. See Threads and Parallel Patterns.

14. Results through a channel (Intermediate)

Square each input number on its own thread and send the answers to the main thread through a channel. Messages arrive in any order, so tag each with its index and return the squares in the original order.

Rust Problem 14: Results through a channel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

Create let (tx, rx) = mpsc::channel();. For each (index, n) clone the sender, move the clone into thread::spawn, and send (index, n * n). After the loop, drop(tx): the receiver's iterator only ends when every sender is gone, including the original. Then rx.iter().collect::<Vec<_>>(), sort by index, and keep the values.

Show solution
Rust
use std::sync::mpsc;
use std::thread;

fn squares_in_threads(inputs: Vec<u32>) -> Vec<u32> {
    let (tx, rx) = mpsc::channel();
    for (index, n) in inputs.into_iter().enumerate() {
        let tx = tx.clone();
        thread::spawn(move || {
            tx.send((index, n * n)).unwrap();
        });
    }
    drop(tx);

    let mut results: Vec<(usize, u32)> = rx.iter().collect();
    results.sort();
    results.into_iter().map(|(_, square)| square).collect()
}

fn main() {
    println!("{:?}", squares_in_threads(vec![1, 2, 3, 4, 5]));
    println!("{:?}", squares_in_threads(vec![]));
    println!("{:?}", squares_in_threads(vec![12]));
}

If you forget drop(tx), the program hangs forever: rx.iter() waits for a sender that is still alive in main. Sorting by the index restores a deterministic result even though thread scheduling is not deterministic. In real code, starting one thread per item is wasteful; use a fixed number of workers. See Channels.

15. Counting words with a Mutex (Challenge)

Each line of text is counted on its own thread, and the threads merge their counts into one shared BTreeMap protected by a Mutex inside an Arc. Keep the locked section short: count locally first, then merge.

Rust Problem 15: Counting words with a Mutex

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Show hint

Create let totals = Arc::new(Mutex::new(BTreeMap::new()));. For each line clone the Arc and spawn a thread that builds a local BTreeMap<String, usize>, then locks (totals.lock().unwrap()) and adds its entries. Keep the join handles and join() them all. At the end, Arc::try_unwrap(totals).unwrap().into_inner().unwrap() takes the map back out once no other owner is left.

Show solution
Rust
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use std::thread;

fn count_words_parallel(lines: Vec<&'static str>) -> BTreeMap<String, usize> {
    let totals = Arc::new(Mutex::new(BTreeMap::new()));

    let handles: Vec<_> = lines
        .into_iter()
        .map(|line| {
            let totals = Arc::clone(&totals);
            thread::spawn(move || {
                let mut local = BTreeMap::new();
                for word in line.split_whitespace() {
                    *local.entry(word.to_lowercase()).or_insert(0usize) += 1;
                }
                let mut guard = totals.lock().unwrap();
                for (word, n) in local {
                    *guard.entry(word).or_insert(0) += n;
                }
            })
        })
        .collect();

    for handle in handles {
        handle.join().unwrap();
    }
    Arc::try_unwrap(totals).unwrap().into_inner().unwrap()
}

fn main() {
    let lines = vec!["the cat sat", "the dog sat", "The end"];
    for (word, n) in count_words_parallel(lines) {
        println!("{word}: {n}");
    }
}

The threads finish in any order, but addition is commutative and the BTreeMap sorts the keys, so the output is the same every time. Counting locally and locking once per thread keeps contention low; locking for every single word would serialize the threads. The guard is released automatically at the end of the closure. Arc::try_unwrap succeeds only because all other clones were dropped when the threads finished. See Mutex and RwLock.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does largest need T: PartialOrd + Copy in problem 2?

    Comparing needs PartialOrd. The function returns a T taken from a &[T], which is only possible without moving out of the slice when T is Copy (otherwise return Option<&T>).
  2. 2. What happens if you forget drop(tx) in the channel problem?

    rx.iter() ends only when all senders are dropped. The original tx in the function would stay alive, so the loop never finishes.
  3. 3. Why is thread::scope able to borrow data while thread::spawn is not?

    A spawned thread requires a 'static closure because it may outlive the caller. A scope joins all its threads before returning, so borrowed data cannot be freed too early.
  4. 4. In problem 12, what does Rc::strong_count(&log) report after two services were created?

    The original log plus one clone per service makes three owners. Dropping one service lowers the count to two.
  5. 5. Why does Tokens::next_word return Option<&'a str> instead of Option<&str>?

    With the elided lifetime the result would borrow from the tokenizer, and calling next_word again would conflict with a word still in use. 'a ties the slices to the text itself.

Summary

  • Traits describe shared behaviour; default methods are written once, and dyn Trait or generics with bounds let you use them.
  • PartialOrd, Copy, Display, FromStr and the std::ops traits are how your types join the language's own syntax.
  • Iterator adapters and a custom Iterator::next replace most manual loops; infinite iterators are fine when something ends the pipeline.
  • Closures capture their environment; FnMut for changing state, move for owning it, Box<dyn Fn> to store different closures together.
  • A good error type is an enum with Display, a source, and enough data (like the position) to be useful.
  • Lifetimes on returned slices say where the data really lives.
  • Rc<RefCell<T>> shares state on one thread; Arc<Mutex<T>>, scoped threads and channels do it across threads, and the results should never depend on scheduling order.

Next: Rust Interview Questions and Answers