Summary - Control flow
- Rust course
- Beginner
- Lesson 41/115
- 5 min
Combine if, match and loops to build a number guessing game.
Control flow summary
Decisions: if/else if/else (bool condition, produces a value as an expression) and match (exhaustive, range and | patterns). Loops: loop (unconditional, break value), while (conditional), for (iterators, ../..=, enumerate, rev). Flow: break, continue, labels ('dis).
for n in 1..=15 {
let s = match (n % 3, n % 5) {
(0, 0) => "FizzBuzz".to_string(),
(0, _) => "Fizz".to_string(),
(_, 0) => "Buzz".to_string(),
_ => n.to_string(),
};
print!("{s} ");
}match on a tuple
Matching several values at once by putting them in a tuple is a readable approach. _ ignores the value at that position:
match (gun_tatil, hava_guzel) {
(true, true) => "pikniğe git",
(true, false) => "film izle",
(false, _) => "işe git",
}Practice FizzBuzz
For the numbers 1 to 15, print FizzBuzz using match (n % 3, n % 5) on a tuple; print the values on one line separated by spaces (print!) and call println!() at the end.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
for n in 1..=15 {
let s = match (n % 3, n % 5) {
(0, 0) => "FizzBuzz".to_string(),
(0, _) => "Fizz".to_string(),
(_, 0) => "Buzz".to_string(),
_ => n.to_string(),
};
print!("{s} ");
}
println!();
}Expected output
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In the FizzBuzz example, why is the <code>(0, 0)</code> arm first?
- match runs the first matching arm; if (0, _) came first, 15 would be "Fizz" Correct answer
- Alphabetical order
- Rust requires it
- Order doesn't matter
Explanation: Arms are tried from top to bottom; the most specific pattern goes on top.
2 Reverse range
for i in (1..=5).____() {
print!("{i} "); // 5 4 3 2 1
}
for i in (1..=5).rev() {
print!("{i} "); // 5 4 3 2 1
}
Explanation: rev() walks the iterator from the end to the start.
3 Group summary
| Term | Meaning |
|---|---|
if |
Two-way decision |
match |
Exhaustive decision |
loop / while |
Unconditional / conditional loop |
for |
Iterator loop |