Skip to content

Instantly share code, notes, and snippets.

@elfsternberg
Last active Feb 8, 2021
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@ValeTheVioletMote ValeTheVioletMote commented Oct 16, 2019

This was an awesome learning experience; Thank you!

@elfsternberg

This comment has been minimized.

Copy link
Owner Author

@elfsternberg elfsternberg commented Oct 21, 2019

@ed-davies

This comment has been minimized.

Copy link

@ed-davies ed-davies commented Dec 26, 2019

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