FizzBuzz Match On Tuple Remainders

Grouping the two remainders into one tuple lets a single match dispatch Fizz, Buzz, and FizzBuzz without nested if branches or repeated modulo checks.

RustData Integrity

Code

rustsnippet
13 lines
fn main() {
    // 把两个余数打包成元组 (tuple),一次 match 同时分派两种整除规则,
    // 避免 if/else 嵌套里命中 %3 后还要重复判断 %5
    for n in 1..=15 {
        let label = match (n % 3, n % 5) {
            (0, 0) => "FizzBuzz".to_string(),
            (0, _) => "Fizz".to_string(),
            (_, 0) => "Buzz".to_string(),
            _ => n.to_string(),
        };
        println!("{n:2} -> {label}");
    }
}

Inside the snippet

The code’s whole job belongs to the function main.

One loop does the cycling here: for n in 1..=15. Pattern matching via match forces each shape of the value to be handled.

Watch out for

  • The toolchain already provides everything it needs in order to run.

Using it

The main signature is written as fn main()

The key statements, annotated

let label = match (n % 3, n % 5) {
    (0, 0) => "FizzBuzz".to_string(),
    (0, _) => "Fizz".to_string(),
    (_, 0) => "Buzz".to_string(),
    _ => n.to_string(),
};

Interactive Tools for This Topic

FAQ

How do you run FizzBuzz Match On Tuple Remainders?
Run the file on its own; every call resolves against the standard surface it already imports.