1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-05-20 01:13:14 +02:00

32 lines
853 B
Markdown
Raw Normal View History

2022-12-21 16:36:30 +01:00
# Functions
A Rust version of the famous [FizzBuzz](https://en.wikipedia.org/wiki/Fizz_buzz) interview question:
2022-12-21 16:36:30 +01:00
```rust,editable
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);
}
}
```