Rust Exercises
Time to practise! Each exercise below gives you a starter program that already compiles and runs, but doesn't do the job yet. Edit the code in the playground, press ▶ Run, and compare your output with the expected result. If you get stuck, open the solution — but try on your own first.
| # | Exercise | Topics |
|---|---|---|
| 1 | Temperature converter | functions, arithmetic |
| 2 | FizzBuzz | loops, if/else, % |
| 3 | Vowel counter | strings, chars(), match |
| 4 | Reverse the words | strings, iterators |
| 5 | Sum of even numbers | vectors, closures |
| 6 | Largest value | Option, slices |
| 7 | Rectangle methods | structs, impl |
| 8 | Word frequency | HashMap, sorting |
| 9 | Safe age parser | Result, error handling |
1. Temperature converter
Complete to_fahrenheit so it converts Celsius to Fahrenheit using F = C × 9 / 5 + 32.
fn to_fahrenheit(celsius: f64) -> f64 {
// TODO: replace this with the real formula
0.0
}
fn main() {
for c in [0.0, 100.0, -40.0, 37.0] {
println!("{}°C = {}°F", c, to_fahrenheit(c));
}
}0°C = 0°F
100°C = 0°F
-40°C = 0°F
37°C = 0°F
Expected: 32, 212, -40 and 98.6.
Show solution
fn to_fahrenheit(celsius: f64) -> f64 {
celsius * 9.0 / 5.0 + 32.0
}
fn main() {
for c in [0.0, 100.0, -40.0, 37.0] {
println!("{}°C = {}°F", c, to_fahrenheit(c));
}
}Output:
0°C = 32°F
100°C = 212°F
-40°C = -40°F
37°C = 98.6°F2. FizzBuzz
Print the numbers 1 to 15, but print Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for multiples of both.
fn main() {
for n in 1..=15 {
// TODO: print Fizz, Buzz or FizzBuzz where needed
println!("{}", n);
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Show solution
fn main() {
for n in 1..=15 {
if n % 15 == 0 {
println!("FizzBuzz");
} else if n % 3 == 0 {
println!("Fizz");
} else if n % 5 == 0 {
println!("Buzz");
} else {
println!("{}", n);
}
}
}Output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzTip: Check
n % 15first. If you testn % 3first, 15 would printFizzand never reach theFizzBuzzbranch.
3. Vowel counter
Make count_vowels return how many vowels (a e i o u, upper or lower case) the text contains.
fn count_vowels(text: &str) -> usize {
let mut count = 0;
// TODO: loop over text.chars() and count the vowels
count
}
fn main() {
println!("{}", count_vowels("Hello World"));
println!("{}", count_vowels("Rustacean"));
println!("{}", count_vowels("rhythm"));
}0
0
0
Expected: 3, 4 and 0.
Show solution
fn count_vowels(text: &str) -> usize {
let mut count = 0;
for c in text.chars() {
match c.to_ascii_lowercase() {
'a' | 'e' | 'i' | 'o' | 'u' => count += 1,
_ => {}
}
}
count
}
fn main() {
println!("{}", count_vowels("Hello World"));
println!("{}", count_vowels("Rustacean"));
println!("{}", count_vowels("rhythm"));
}Output:
3
4
04. Reverse the words
Return a new String with the words of the sentence in reverse order. Hint: split_whitespace(), rev() and join(" ").
fn reverse_words(sentence: &str) -> String {
// TODO: reverse the order of the words
sentence.to_string()
}
fn main() {
println!("{}", reverse_words("rust is really fun"));
println!("{}", reverse_words("one"));
}rust is really fun
one
Expected: fun really is rust and one.
Show solution
fn reverse_words(sentence: &str) -> String {
let words: Vec<&str> = sentence.split_whitespace().rev().collect();
words.join(" ")
}
fn main() {
println!("{}", reverse_words("rust is really fun"));
println!("{}", reverse_words("one"));
}Output:
fun really is rust
one5. Sum of even numbers
Use an iterator chain with filter and sum to add up only the even numbers.
fn sum_even(numbers: &[i32]) -> i32 {
// TODO: keep only even numbers, then add them up
numbers.iter().sum()
}
fn main() {
let data = vec![3, 8, 11, 14, 20, 7];
println!("sum of evens: {}", sum_even(&data));
}sum of evens: 63
Expected: sum of evens: 42.
Show solution
fn sum_even(numbers: &[i32]) -> i32 {
numbers.iter().filter(|n| *n % 2 == 0).sum()
}
fn main() {
let data = vec![3, 8, 11, 14, 20, 7];
println!("sum of evens: {}", sum_even(&data));
}Output:
sum of evens: 426. Largest value
Return the largest number in the slice wrapped in Some, or None if the slice is empty. Write the loop yourself instead of using .max().
fn largest(numbers: &[i32]) -> Option<i32> {
// TODO: return None for an empty slice, otherwise Some(largest)
None
}
fn main() {
println!("{:?}", largest(&[4, 19, -2, 7]));
println!("{:?}", largest(&[-5, -9]));
println!("{:?}", largest(&[]));
}None
None
None
Expected: Some(19), Some(-5) and None.
Show solution
fn largest(numbers: &[i32]) -> Option<i32> {
if numbers.is_empty() {
return None;
}
let mut best = numbers[0];
for &n in numbers {
if n > best {
best = n;
}
}
Some(best)
}
fn main() {
println!("{:?}", largest(&[4, 19, -2, 7]));
println!("{:?}", largest(&[-5, -9]));
println!("{:?}", largest(&[]));
}Output:
Some(19)
Some(-5)
None7. Rectangle methods
Implement the area and is_square methods for Rectangle.
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
// TODO
0
}
fn is_square(&self) -> bool {
// TODO
false
}
}
fn main() {
let shapes = [
Rectangle { width: 4, height: 6 },
Rectangle { width: 5, height: 5 },
];
for r in &shapes {
println!("{}x{}: area {}, square: {}", r.width, r.height, r.area(), r.is_square());
}
}4x6: area 0, square: false
5x5: area 0, square: false
Expected: areas 24 and 25; only the second one is a square.
Show solution
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn is_square(&self) -> bool {
self.width == self.height
}
}
fn main() {
let shapes = [
Rectangle { width: 4, height: 6 },
Rectangle { width: 5, height: 5 },
];
for r in &shapes {
println!("{}x{}: area {}, square: {}", r.width, r.height, r.area(), r.is_square());
}
}Output:
4x6: area 24, square: false
5x5: area 25, square: true8. Word frequency
Count how often each word appears, then print the words in alphabetical order with their counts. A HashMap has no fixed order, so collect its entries into a Vec and sort it before printing.
use std::collections::HashMap;
fn main() {
let text = "the cat and the dog and the bird";
let mut counts: HashMap<&str, u32> = HashMap::new();
// TODO: fill `counts` using text.split_whitespace()
let mut entries: Vec<(&str, u32)> = counts.into_iter().collect();
entries.sort();
println!("{} distinct words", entries.len());
for (word, n) in entries {
println!("{}: {}", word, n);
}
}0 distinct words
Show solution
use std::collections::HashMap;
fn main() {
let text = "the cat and the dog and the bird";
let mut counts: HashMap<&str, u32> = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
let mut entries: Vec<(&str, u32)> = counts.into_iter().collect();
entries.sort();
println!("{} distinct words", entries.len());
for (word, n) in entries {
println!("{}: {}", word, n);
}
}Output:
5 distinct words
and: 2
bird: 1
cat: 1
dog: 1
the: 39. Safe age parser
parse_age should turn text into a u32 age. Return Err with a helpful message if the text is not a number, or if the age is above 150.
fn parse_age(input: &str) -> Result<u32, String> {
// TODO: use input.trim().parse::<u32>() and check the range
Ok(0)
}
fn main() {
for text in ["42", " 7 ", "abc", "200"] {
match parse_age(text) {
Ok(age) => println!("{:?} -> age {}", text, age),
Err(msg) => println!("{:?} -> error: {}", text, msg),
}
}
}"42" -> age 0
" 7 " -> age 0
"abc" -> age 0
"200" -> age 0
Show solution
fn parse_age(input: &str) -> Result<u32, String> {
let age: u32 = input
.trim()
.parse()
.map_err(|_| format!("'{}' is not a number", input.trim()))?;
if age > 150 {
return Err(format!("{} is not a realistic age", age));
}
Ok(age)
}
fn main() {
for text in ["42", " 7 ", "abc", "200"] {
match parse_age(text) {
Ok(age) => println!("{:?} -> age {}", text, age),
Err(msg) => println!("{:?} -> error: {}", text, msg),
}
}
}Output:
"42" -> age 42
" 7 " -> age 7
"abc" -> error: 'abc' is not a number
"200" -> error: 200 is not a realistic ageTest yourself
In FizzBuzz, why should you test n % 15 == 0 before n % 3 == 0?
- Because
%only works with 15 - Otherwise multiples of 15 would match the
Fizzbranch first - It makes the loop run faster
- Rust requires the largest number first
Which expression increments a word's count in a HashMap<&str, u32>, inserting 0 first if needed?
counts[word] += 1counts.insert(word, +1)*counts.entry(word).or_insert(0) += 1counts.get(word) + 1
What does the ? operator do inside a function returning Result?
- Prints the error
- Returns the error early if the value is
Err, otherwise unwrapsOk - Converts the error into a panic
- Ignores the error