1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2024-11-26 01:30:22 +02:00

Simplify fizz buzz slide (#595)

There is no need to introduce `match` here where we don’t have time to
talk about it in detail.
This commit is contained in:
Martin Geisler 2023-05-03 09:56:58 +02:00 committed by GitHub
parent 3b21053ff2
commit 4a09d053ac
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -4,28 +4,28 @@ A Rust version of the famous [FizzBuzz](https://en.wikipedia.org/wiki/Fizz_buzz)
```rust,editable
fn main() {
fizzbuzz_to(20); // Defined below, no forward declaration needed
print_fizzbuzz_to(20);
}
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
if rhs == 0 {
return false; // Corner case, early return
fn is_divisible(n: u32, divisor: u32) -> bool {
if divisor == 0 {
return false;
}
lhs % rhs == 0 // The last expression in a block is the return value
n % divisor == 0
}
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(n: u32) -> String {
let fizz = if is_divisible(n, 3) { "fizz" } else { "" };
let buzz = if is_divisible(n, 5) { "buzz" } else { "" };
if fizz.is_empty() && buzz.is_empty() {
return format!("{n}");
}
format!("{fizz}{buzz}")
}
fn fizzbuzz_to(n: u32) { // `-> ()` is normally omitted
fn print_fizzbuzz_to(n: u32) {
for i in 1..=n {
fizzbuzz(i);
println!("{}", fizzbuzz(i));
}
}
```
@ -36,19 +36,6 @@ fn fizzbuzz_to(n: u32) { // `-> ()` is normally omitted
* Declaration parameters are followed by a type (the reverse of some programming languages), then a return type.
* The last expression in a function body (or any block) becomes the return value. Simply omit the `;` at the end of the expression.
* Some functions have no return value, and return the 'unit type', `()`. The compiler will infer this if the `-> ()` return type is omitted.
* The range expression in the `for` loop in `fizzbuzz_to()` contains `=n`, which causes it to include the upper bound.
* The `match` expression in `fizzbuzz()` is doing a lot of work. It is expanded below to show what is happening.
(Type annotations added for clarity, but they can be elided.)
```rust,ignore
let by_3: bool = is_divisible_by(n, 3);
let by_5: bool = is_divisible_by(n, 5);
let by_35: (bool, bool) = (by_3, by_5);
match by_35 {
// ...
```
* The range expression in the `for` loop in `print_fizzbuzz_to()` contains `=n`, which causes it to include the upper bound.
</details>