|
|
|
|
|
by stefano_c
1518 days ago
|
|
One possible solution in Rust could be: enum Value {
Fizz,
Buzz,
FizzBuzz,
Number(usize),
}
impl std::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Value::Fizz => write!(f, "Fizz"),
Value::Buzz => write!(f, "Buzz"),
Value::FizzBuzz => write!(f, "FizzBuzz"),
Value::Number(num) => write!(f, "{}", num),
}
}
}
const fn get_fizzbuzz_equivalent(number: usize) -> Value {
if number % 15 == 0 {
Value::FizzBuzz
} else if number % 3 == 0 {
Value::Fizz
} else if number % 5 == 0 {
Value::Buzz
} else {
Value::Number(number)
}
}
fn main() {
(1..100).for_each(|num| println!("{}", get_fizzbuzz_equivalent(num)));
}
|
|
You annotate get_fizzbuzz_equivalent() with const, so Rust would evaluate that on constant inputs at compile time, but that's not very interesting since it's basically a switch.
The use of const here does not oblige Rust to somehow figure out everywhere you can use this function and do the work at compile time since the inputs might be (and are here) variables. Sure enough if you try in Godbolt you will see that eliding const makes no real difference.
Rust's const today is far less powerful than something like C++ constexpr, I suspect that you can't really do what Nim did in a reasonable way with Rust. You could I'm sure get there with build.rs and/or proc macros, but that's not really in the spirit of this exercise.