Skip to content

Instantly share code, notes, and snippets.

@elfsternberg
Last active February 8, 2021 08:11
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elfsternberg/4757b918d034e5a1820704af6b94d82d to your computer and use it in GitHub Desktop.
Save elfsternberg/4757b918d034e5a1820704af6b94d82d to your computer and use it in GitHub Desktop.
Pedantic FizzBuzz implementation in Rust
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));
}
}
@ValeTheVioletMote
Copy link

This was an awesome learning experience; Thank you!

@elfsternberg
Copy link
Author

elfsternberg commented Oct 21, 2019 via email

@ed-davies
Copy link

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”.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment