This would be a nice fizzbuzz in Rust I think:
match (i % 3, i % 5) {
(0, 0) => println!("FizzBuzz"),
(0, _) => println!("Fizz"),
(_, 0) => println!("Buzz"),
_ => println!("{}", i),
}
It could also be stated this way:
match i {
i if i % 3 == 0 && i % 5 == 0 => println!("FizzBuzz"),
i if i % 3 == 0 => println!("Fizz"),
i if i % 5 == 0 => println!("Buzz"),
_ => println!("{}", i),
}
Now that confused me.
i if i % 3 == 0
is an expression, right? So, this evaluates to i when the condition is true. But what happens if it is false?
Now that confused me.
i if i % 3 == 0is an expression, right?
No, it is not. It is a pattern (i) with a guard (i % 3 == 0). Maybe you got confused because you used the same bind name. Consider this modified example:
match i {
x if x % 3 == 0 && x % 5 == 0 => println!("FizzBuzz"),
x if x % 3 => println!("Fizz"),
x if x % 5 => println!("Buzz"),
_ => println!("{}", x),
}
You can read the match expression like this
i matches the pattern x (it always match and i value is moved (copied) to x) and x % 3 == 0 and x % 5 == 0 then println!("FizzBuzz"); elsei matches the pattern x and x % 3 == 0 then println!("Fizz"); elsei matches the pattern x and x % 5 == 0 then println!("Buzz"); elseprintln!("{}", x)If it is false, the match arm is simply not called. These are called guards in the match statement. You can read about them in the book.
They are similar to an if-else but not in the case that there is an else block. They just add more filtering to the match blocks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With