1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-05-19 08:53:12 +02:00
Andrew Pollack 9c1a1a6d90
Add link to FizzBuzz definition
For those who are lucky enough to not know what FizzBuzz intends to accomplish 😹
2022-12-21 09:30:55 -08:00

853 B

Functions

A Rust version of the famous FizzBuzz interview question:

fn main() {
    fizzbuzz_to(20);   // Defined below, no forward declaration needed
}

fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
    if rhs == 0 {
        return false;  // Corner case, early return
    }
    lhs % rhs == 0     // The last expression is the return value
}

fn fizzbuzz(n: u32) -> () {  // No return value means returning the unit type `()`
    match (is_divisible_by(n, 3), is_divisible_by(n, 5)) {
        (true,  true)  => println!("fizzbuzz"),
        (true,  false) => println!("fizz"),
        (false, true)  => println!("buzz"),
        (false, false) => println!("{n}"),
    }
}

fn fizzbuzz_to(n: u32) {  // `-> ()` is normally omitted
    for n in 1..=n {
        fizzbuzz(n);
    }
}