Skip to content
Tutorials Center
My learning

Topics

Lesson 128 of 132 ยท Practice and Review

Practice Problems: Fundamentals

15 graded Rust practice problems with hints and verified solutions: loops, numbers, strings, ownership, structs, enums, Option and Result. Run Rust in your browser.

You learn Rust by writing Rust, and above all by arguing with the compiler until it agrees with you. Lessons build understanding; only practice builds the reflexes: reaching for an iterator instead of a counter loop, borrowing instead of cloning, returning Option instead of a magic number. This page collects 15 problems that cover the first half of the course, ordered from easy to harder.

Every problem has a short task, an editor with starter code, a hint and a hidden solution. The starter code compiles and runs as given: the function you must write is a stub that returns a placeholder, and the comments in main show the output you should get once your code works. Replace the stub body, press Run and compare. (One problem, number 11, starts with a program that does not compile, because fixing compiler errors is a skill of its own.)

  • Try first, peek later. Give every problem a real attempt before you open the hint, and the hint before the solution. Being stuck for a few minutes is where the learning happens.
  • Compare, don't copy. Your solution can look different from ours and still be right. Read ours for ideas, then see whether yours can be shorter or clearer.
  • Read the compiler. Rust reports the exact line and column of a mistake and usually suggests a fix. Reading Compiler Errors explains the common messages.
  • Test the edges. Zero, empty input, one element, negative numbers and non-English text are where programs break. Most problems include an edge case in their test calls.

Keep the cheat sheet open in another tab. When you finish these, move on to Traits, Iterators and Concurrency.

Numbers and control flow

These problems practice variables, scalar types, loops and if expressions.

1. Multiples of 3 or 5 (Beginner)

Write sum_multiples(limit) that returns the sum of all numbers below limit that are multiples of 3 or of 5. For 10 the numbers are 3, 5, 6 and 9, which add up to 23.

Rust Problem 1: Multiples of 3 or 5

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

A range 1..limit already excludes limit. Combine filter with the % operator, then sum(). Test for "3 or 5" with ||, so that 15 is counted only once.

Show solution
Rust
fn sum_multiples(limit: u32) -> u32 {
    (1..limit).filter(|n| n % 3 == 0 || n % 5 == 0).sum()
}

fn main() {
    println!("{}", sum_multiples(10));
    println!("{}", sum_multiples(1000));
    println!("{}", sum_multiples(1));
}

Because the condition is a single ||, a number such as 15 passes the filter once. Adding "multiples of 3" and "multiples of 5" separately would count it twice. sum() needs to know the result type, and the return type u32 provides it.

2. Temperature table (Beginner)

Write celsius_to_fahrenheit using F = C * 9 / 5 + 32. The loop in main prints a table from 0 to 100 degrees in steps of 20, with right-aligned columns.

Rust Problem 2: Temperature table

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

Rust never mixes integers and floats silently, so write the literals as 9.0, 5.0 and 32.0. The format spec {:>5.1} means "right-aligned in 5 columns, one decimal".

Show solution
Rust
fn celsius_to_fahrenheit(c: f64) -> f64 {
    c * 9.0 / 5.0 + 32.0
}

fn main() {
    for c in (0..=100).step_by(20) {
        println!("{c:>3} C = {:>5.1} F", celsius_to_fahrenheit(c as f64));
    }
}

The function body is one expression with no semicolon, so it is the return value. c as f64 converts the loop's i32 to a float; for a lossless conversion you could also write f64::from(c).

3. Leap years (Beginner)

A year is a leap year if it is divisible by 4, except years divisible by 100, unless they are also divisible by 400. Implement is_leap.

Rust Problem 3: Leap years

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

You can write the whole rule as one boolean expression: (divisible by 4 and not by 100) or divisible by 400. Remember that == has higher precedence than &&, which has higher precedence than ||, but add parentheses anyway for readability.

Show solution
Rust
fn is_leap(year: i32) -> bool {
    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}

fn main() {
    for year in [1900, 2000, 2023, 2024] {
        println!("{year}: {}", is_leap(year));
    }
}

1900 is divisible by 100 but not 400, so it is not a leap year; 2000 is divisible by 400, so it is. Iterating over an array by value (for year in [..]) works in edition 2021 and later.

4. Collatz steps (Beginner)

Start with a positive number. If it is even, halve it; if it is odd, triple it and add 1. Repeat until you reach 1. Write collatz_steps that counts how many steps it takes.

Rust Problem 4: Collatz steps

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

Use a while n != 1 loop with a counter, and an if n % 2 == 0 { ... } else { ... } inside. The parameter is already declared mut, so you may change n directly.

Show solution
Rust
fn collatz_steps(mut n: u64) -> u32 {
    let mut steps = 0;
    while n != 1 {
        n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };
        steps += 1;
    }
    steps
}

fn main() {
    println!("{}", collatz_steps(1));
    println!("{}", collatz_steps(6));
    println!("{}", collatz_steps(27));
}

if is an expression, so it can sit on the right of an assignment. Note that collatz_steps(0) would loop forever (0 is even and halves to 0). A production version would return an Option or reject zero, which is a good extension exercise.

5. Digit tricks (Beginner)

Implement digit_sum (the sum of the decimal digits) and reverse_number (the digits in reverse order) using only arithmetic, without converting to a string.

Rust Problem 5: Digit tricks

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

n % 10 is the last digit and n / 10 removes it. Loop while n > 0. For the reversal, each time shift what you have so far one place left (result * 10) and add the new digit.

Show solution
Rust
fn digit_sum(mut n: u64) -> u64 {
    let mut sum = 0;
    while n > 0 {
        sum += n % 10;
        n /= 10;
    }
    sum
}

fn reverse_number(mut n: u64) -> u64 {
    let mut result = 0;
    while n > 0 {
        result = result * 10 + n % 10;
        n /= 10;
    }
    result
}

fn main() {
    println!("{}", digit_sum(12345));
    println!("{}", digit_sum(0));
    println!("{}", reverse_number(12345));
    println!("{}", reverse_number(12340));
}

The trailing zero of 12340 disappears because it becomes a leading zero (04321). In debug builds, a huge input could overflow result * 10 and panic, which is Rust telling you the problem is not well defined for every u64.

6. Sum the numbers from input (Beginner)

Read one line from the Input box that contains numbers separated by spaces. Print the sum, how many numbers were valid, and how many tokens were ignored because they are not numbers.

Rust Problem 6: Sum the 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

line.split_whitespace() yields the tokens, and token.parse::<i64>() returns a Result. Use match on it: add to the sum on Ok, count an ignored token on Err.

Show solution
Rust
use std::io;

fn main() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("failed to read");

    let mut sum = 0;
    let mut numbers = 0;
    let mut ignored = 0;
    for token in line.split_whitespace() {
        match token.parse::<i64>() {
            Ok(n) => {
                sum += n;
                numbers += 1;
            }
            Err(_) => ignored += 1,
        }
    }
    println!("sum = {sum}, numbers = {numbers}, ignored = {ignored}");
}

read_line keeps the newline, but split_whitespace skips it. Turning a failed parse into "ignore it" is a policy decision; a stricter program would report the bad token. See Reading Input.

Strings

These problems practice string basics and strings.

7. Palindromes (Easy)

A phrase is a palindrome if it reads the same forwards and backwards when you ignore case, spaces and punctuation. Implement is_palindrome.

Rust Problem 7: Palindromes

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

Build a Vec<char> of only the alphanumeric characters (c.is_alphanumeric()), lowercased. Then compare it with its own reverse: iterators have rev(), and Iterator::eq compares two iterators element by element.

Show solution
Rust
fn is_palindrome(text: &str) -> bool {
    let cleaned: Vec<char> = text
        .chars()
        .filter(|c| c.is_alphanumeric())
        .flat_map(|c| c.to_lowercase())
        .collect();
    cleaned.iter().eq(cleaned.iter().rev())
}

fn main() {
    println!("{}", is_palindrome("A man, a plan, a canal: Panama"));
    println!("{}", is_palindrome("Rust"));
    println!("{}", is_palindrome(""));
    println!("{}", is_palindrome("No lemon, no melon"));
}

We iterate over chars(), not bytes, so accented letters work. to_lowercase() returns an iterator (a few letters lowercase to more than one character), which is why flat_map is used. The empty string is a palindrome by convention.

8. Word frequencies (Easy)

Count how often each word appears in a text (case-insensitive) and print the words in alphabetical order, one word: count per line.

Rust Problem 8: Word frequencies

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

counts.entry(key).or_insert(0) returns a &mut u32 that you can increment with *... += 1. A BTreeMap keeps its keys sorted, so the printing order comes for free (a HashMap would print in a random order). Lowercase each word with to_lowercase().

Show solution
Rust
use std::collections::BTreeMap;

fn word_counts(text: &str) -> BTreeMap<String, u32> {
    let mut counts = BTreeMap::new();
    for word in text.split_whitespace() {
        *counts.entry(word.to_lowercase()).or_insert(0) += 1;
    }
    counts
}

fn main() {
    let counts = word_counts("The cat and the hat and THE bat");
    for (word, n) in &counts {
        println!("{word}: {n}");
    }
}

The entry API does one lookup for "find or create", which is both shorter and faster than contains_key followed by insert. See HashMap.

9. Caesar cipher (Easy)

Shift every letter by k places in the alphabet, wrapping from z to a, keep upper and lower case, and leave other characters alone. Decoding is shifting by 26 - k.

Rust Problem 9: Caesar cipher

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

Match on the character with ranges: 'a'..='z' and 'A'..='Z'. For a letter, compute (c as u8 - base + shift) % 26 + base, where base is b'a' or b'A'. Finally collect() the mapped characters into a String.

Show solution
Rust
fn rotate(c: char, base: u8, shift: u8) -> char {
    (((c as u8 - base + shift) % 26) + base) as char
}

fn caesar(text: &str, shift: u8) -> String {
    text.chars()
        .map(|c| match c {
            'a'..='z' => rotate(c, b'a', shift),
            'A'..='Z' => rotate(c, b'A', shift),
            _ => c,
        })
        .collect()
}

fn main() {
    let secret = caesar("Hello, World!", 3);
    println!("{secret}");
    println!("{}", caesar(&secret, 23));
    println!("{}", caesar("xyz", 3));
}

Inside the two ranges c is plain ASCII, so casting to u8 is safe. collect() can build a String from an iterator of char. For shifts above 229 the u8 sum could overflow (and panic in debug builds); reduce the shift with % 26 first if you accept any value.

10. Longest word (Intermediate)

Return the first longest word of a text as a slice of the original text, without allocating a new String. If there are no words, return an empty string.

Rust Problem 10: Longest word

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

Keep a best: &str that starts as "". For each word from split_whitespace(), replace best only if the word is strictly longer (>), so that the first of equal-length words wins. The lifetime of the return value is tied to the single input, so no annotations are needed (lifetime elision).

Show solution
Rust
fn longest_word(text: &str) -> &str {
    let mut best = "";
    for word in text.split_whitespace() {
        if word.len() > best.len() {
            best = word;
        }
    }
    best
}

fn main() {
    println!("{}", longest_word("the quick brown fox jumped"));
    println!("{}", longest_word("aa bb cc"));
    println!("[{}]", longest_word(""));
}

Every &str returned here points into text, so nothing is copied. With one reference parameter the compiler assigns its lifetime to the result automatically. len() counts bytes, so for non-ASCII text you may prefer word.chars().count().

Ownership, structs and enums

These problems practice ownership, borrowing, structs, methods and enums.

11. Fix the compile error (Intermediate)

This program does not compile. Read the error and fix it so that it prints 2 words, 8 bytes. Do not clone the vector: change the function to borrow its argument.

Rust Problem 11: Fix the compile error (fails on purpose)

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.

The compiler stops with error[E0382]: borrow of moved value: words``, labelling words as "value moved here" at the call and "value borrowed here after move" in words.len(). A note even suggests changing the parameter type to borrow instead.

Show hint

The function only needs to read the strings, so it should not take ownership. Accept &[String] (a slice reference works for Vec, arrays and slices) and call it with &words.

Show solution
Rust
fn total_length(words: &[String]) -> usize {
    words.iter().map(|w| w.len()).sum()
}

fn main() {
    let words = vec![String::from("one"), String::from("three")];
    let n = total_length(&words);
    println!("{} words, {} bytes", words.len(), n);
}

&Vec<String> coerces to &[String] automatically. Prefer &[T] over &Vec<T> in parameters, and &str over &String: callers can pass more kinds of data and you lose nothing. This is the usual cure for E0382 when a function only needs to look.

12. A Rectangle type (Intermediate)

Define the methods for a Rectangle: a constructor new, a square helper, area, perimeter, and can_hold(&self, other: &Rectangle) that is true when the other fits inside (strictly smaller in both dimensions).

Rust Problem 12: A Rectangle 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

Methods that only read use &self. new and square have no self, which makes them associated functions, called with Rectangle::new(...). square can simply call new with the same side twice. Struct field shorthand: Self { width, height }.

Show solution
Rust
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn new(width: u32, height: u32) -> Self {
        Self { width, height }
    }

    fn square(side: u32) -> Self {
        Self::new(side, side)
    }

    fn area(&self) -> u32 {
        self.width * self.height
    }

    fn perimeter(&self) -> u32 {
        2 * (self.width + self.height)
    }

    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

fn main() {
    let big = Rectangle::new(8, 5);
    let small = Rectangle::new(3, 2);
    println!("{}", big.area());
    println!("{}", big.perimeter());
    println!("{}", big.can_hold(&small));
    println!("{}", small.can_hold(&big));
    println!("{}", Rectangle::square(4).area());
    println!("{big:?}");
}

can_hold borrows other, so big and small stay usable afterwards. An extension: make new return Option<Rectangle> and reject zero sizes.

13. Shapes with an enum (Intermediate)

Model three shapes as an enum and compute their area with match. Because match must be exhaustive, adding a fourth shape later will make the compiler show you every place to update.

Rust Problem 13: Shapes with an enum

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

match shape { Shape::Circle(r) => ..., Shape::Rect { width, height } => ..., ... }. Because shape is a reference, the bindings are references too; Rust's match ergonomics let you use them in arithmetic after dereferencing (r * r works on &f64 thanks to operator impls, but PI * r * r is clearest with *r).

Show solution
Rust
use std::f64::consts::PI;

enum Shape {
    Circle(f64),
    Rect { width: f64, height: f64 },
    Triangle { base: f64, height: f64 },
}

fn area(shape: &Shape) -> f64 {
    match shape {
        Shape::Circle(r) => PI * r * r,
        Shape::Rect { width, height } => width * height,
        Shape::Triangle { base, height } => 0.5 * base * height,
    }
}

fn main() {
    let shapes = [
        Shape::Circle(1.5),
        Shape::Rect { width: 4.0, height: 2.5 },
        Shape::Triangle { base: 3.0, height: 4.0 },
    ];
    for shape in &shapes {
        println!("{:.2}", area(shape));
    }
}

There is no wildcard arm on purpose. Compare with a class hierarchy: there you add a subclass and hope nobody forgets a switch; here the compiler reports E0004: non-exhaustive patterns. Later you can turn this into a trait with an area method (see Traits) and choose between the two designs.

Option and Result

These problems practice Option, Result and the ? operator.

14. Second largest (Intermediate)

Return the second largest distinct value of a slice as an Option<i32>: None if there are fewer than two distinct values. Do it in a single pass without sorting.

Rust Problem 14: Second 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

Keep two Option<i32> variables, largest and second, both starting as None. For each value n, there are three cases: it beats the largest (the old largest becomes second), it sits strictly between second and largest, or it is irrelevant. A match on largest with guards (Some(l) if n > l => ...) handles this neatly. Option::is_none_or (Rust 1.82) is handy for "no second yet, or n beats it".

Show solution
Rust
fn second_largest(values: &[i32]) -> Option<i32> {
    let mut largest: Option<i32> = None;
    let mut second: Option<i32> = None;
    for &n in values {
        match largest {
            None => largest = Some(n),
            Some(l) if n > l => {
                second = largest;
                largest = Some(n);
            }
            Some(l) if n < l && second.is_none_or(|s| n > s) => second = Some(n),
            _ => {}
        }
    }
    second
}

fn main() {
    println!("{:?}", second_largest(&[3, 9, 9, 5]));
    println!("{:?}", second_largest(&[7]));
    println!("{:?}", second_largest(&[]));
    println!("{:?}", second_largest(&[4, 4]));
    println!("{:?}", second_largest(&[-1, -7, -3]));
}

Using Option instead of a sentinel like i32::MIN makes the "not enough data" case impossible to ignore, and it handles negative numbers correctly. The last arm _ => {} covers duplicates of the largest and values below the current second.

15. Parse key=value pairs (Challenge)

Write parse_pair for lines such as age = 42. It returns Ok((key, number)), or an Err(String) describing what is wrong: the = is missing, the key is empty, or the value is not a number. Use ? rather than nested match blocks.

Rust Problem 15: Parse key=value pairs

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

line.split_once('=') returns an Option<(&str, &str)>. Turn None into an error with ok_or_else(|| format!(...))?. Trim both parts. For the number, value.parse::<i32>() returns a Result whose error type is ParseIntError; convert it into a String with map_err(|e| format!(...))?, because ? requires the error types to match.

Show solution
Rust
fn parse_pair(line: &str) -> Result<(String, i32), String> {
    let (key, value) = line
        .split_once('=')
        .ok_or_else(|| format!("missing '=' in {line:?}"))?;
    let key = key.trim();
    if key.is_empty() {
        return Err(String::from("empty key"));
    }
    let value = value.trim();
    let number = value
        .parse::<i32>()
        .map_err(|e| format!("bad number {value:?}: {e}"))?;
    Ok((key.to_string(), number))
}

fn main() {
    for line in ["age = 42", "score=-7", "height", "=5", "level=x"] {
        match parse_pair(line) {
            Ok((key, n)) => println!("ok: {key} -> {n}"),
            Err(msg) => println!("error: {msg}"),
        }
    }
}

Each ? either unwraps the success value or returns the error from the function immediately, so the happy path reads top to bottom. Using String as the error type keeps this exercise short; in real code you would define an error enum (see Custom Errors) so callers can react to each case.

What next

If these felt comfortable, try the advanced problems, where you write traits, iterator chains, closures and threads. If one of them stumped you, the lesson links in each section are the best place to review. A good habit is to redo a problem you struggled with a week later, from scratch, without looking.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is (1..limit) a good fit for 'numbers below limit'?

    A range a..b is half-open: it contains a but not b. Use a..=b when the end value should be included.
  2. 2. Why is &[String] a better parameter type than Vec<String> for a function that only reads the data?

    Taking Vec<String> moves the vector into the function, so the caller can no longer use it (E0382). A slice reference only borrows, and also accepts arrays and slices.
  3. 3. Which map type prints its entries in sorted key order?

    BTreeMap keeps keys sorted. HashMap iteration order is unspecified and changes from run to run.
  4. 4. What does the ? operator do when the value is an Err?

    On Ok(v) it evaluates to v; on Err(e) it returns Err(From::from(e)) from the enclosing function, which must return a compatible Result.
  5. 5. Why is it useful that match on an enum has no wildcard arm in problem 13?

    Without _, adding a variant makes each non-exhaustive match a compile error (E0004), so you cannot forget to handle the new case.

Summary

  • Practice works best as try, hint, solution, then redo a week later.
  • Ranges, filter, map and sum replace most counter loops; % and / solve digit problems without strings.
  • Work on chars() for text, remember len() counts bytes, and return &str slices of the input to avoid copying.
  • Borrow with &T or &[T] in parameters; E0382 usually means "you only needed to look".
  • Structs hold data, impl blocks hold behaviour, and enums with exhaustive match model "one of several things".
  • Use Option for absent values and Result with ? for failures that carry a reason.

Next: Practice Problems: Traits, Iterators and Concurrency