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 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)); | |
} | |
} |
You're welcome!
…On Wed, Oct 16, 2019 at 1:37 PM Vale the Violet Mote < ***@***.***> wrote:
This was an awesome learning experience; Thank you!
—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
<https://gist.github.com/4757b918d034e5a1820704af6b94d82d?email_source=notifications&email_token=AAA37ZGSJXK6VPTI65KXS5DQO53QRA5CNFSM4JBQYQAKYY3PNVWWK3TUL52HS4DFVNDWS43UINXW23LFNZ2KUY3PNVWWK3TUL5UWJTQAF2TQY#gistcomment-3057420>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAA37ZFH5PLUNUYFMLMHJWDQO53QRANCNFSM4JBQYQAA>
.
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
This was an awesome learning experience; Thank you!