Write the classic FizzBuzz exercise with a for range and a match
Write fizzbuzz(n), which prints the numbers from 1 to n inclusive, one per line, printing Fizz instead of a multiple of 3, Buzz instead of a multiple of 5 and FizzBuzz instead of a multiple of both.
Constraints:
- Loop with
forover a range — no manual counter and nowhile. - Choose each line with one
matchon the pair of remainders(i % 3, i % 5), with no nestedif/else ifchain. fizzbuzz(15)prints 15 lines, the last of themFizzBuzz.
fn fizzbuzz(n: u32) {
// your code here
}Write the implementation.
Loop for i in 1..=n, since the inclusive range reaches n, and match on (i % 3, i % 5): (0, 0) prints FizzBuzz, (0, _) Fizz, (_, 0) Buzz and _ the number. The first matching arm wins, so (0, 0) must come first.
- Writing
1..n, which stops beforenand drops the last number - Putting
(0, 0)after(0, _), so multiples of 15 printFizzand the arm is unreachable - Reaching for a
whilecounter withi++, althoughforover a range needs none and Rust has no++
- How would you return the lines as a
Vec<String>instead of printing them? - Why does the compiler warn when
(0, 0)comes after(0, _)?
The range 1..=n includes its end, so the loop reaches n itself. One match on the pair of remainders (i % 3, i % 5) replaces the if/else if chain: the pattern (0, 0) catches multiples of 15, (0, _) multiples of 3, (_, 0) multiples of 5, and _ everything else.
fn fizzbuzz(n: u32) {
for i in 1..=n {
match (i % 3, i % 5) {
(0, 0) => println!("FizzBuzz"),
(0, _) => println!("Fizz"),
(_, 0) => println!("Buzz"),
_ => println!("{i}"),
}
}
}
fn main() {
fizzbuzz(15); // 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
}Arms are tried from top to bottom, and the first one that matches wins. Put (0, 0) after (0, _) and 15 prints Fizz, while the compiler warns unreachable pattern: the (0, 0) arm can never be reached. The final _ arm is required because a match must be exhaustive: without it, pairs such as (1, 1) would have no arm and the code would not compile.