Last active
February 8, 2021 08:11
-
-
Save elfsternberg/4757b918d034e5a1820704af6b94d82d to your computer and use it in GitHub Desktop.
Pedantic FizzBuzz implementation in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fmt; | |
enum FizzBuzzOr { | |
Fizzbuzz(&'static str), | |
Or(i32) | |
} | |
impl fmt::Display for FizzBuzzOr { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
use FizzBuzzOr::*; | |
match self { | |
Fizzbuzz(a) => write!(f, "{}", a), | |
Or(i) => write!(f, "{}", i) | |
} | |
} | |
} | |
fn fizzbuzz(i: i32) -> FizzBuzzOr { | |
match (i % 3, i % 5) { | |
// The order is important; the more precise definitions | |
// must come before those that use wildcards, or the | |
// wildcarded definitions will pick up incorrect | |
// answers. | |
(0, 0) => FizzBuzzOr::Fizzbuzz("fizzbuzz"), | |
(0, _) => FizzBuzzOr::Fizzbuzz("fizz"), | |
(_, 0) => FizzBuzzOr::Fizzbuzz("buzz"), | |
(_, _) => FizzBuzzOr::Or(i), | |
} | |
} | |
fn main() { | |
for i in 1 .. 100 { | |
println!("{}", fizzbuzz(i)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Neat use of match but
https://www.snoyman.com/blog/2018/10/rust-crash-course-01-kick-the-tires
says to “Print the numbers 1 to 100” whereas this code only does 1 to 99. You need “1 .. 101” or “1 ..= 100”.