Created
June 15, 2015 23:51
-
-
Save Havvy/59aae43ffe05a78c10b6 to your computer and use it in GitHub Desktop.
I went with using an Iterator instead of the traditional if/else chain.
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 FizzBuzz { | |
Fizz, | |
Buzz, | |
} | |
impl fmt::Display for FizzBuzz { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
match self { | |
&FizzBuzz::Fizz => write!(f, "Fizz"), | |
&FizzBuzz::Buzz => write!(f, "Buzz") | |
} | |
} | |
} | |
struct FizzBuzzIter { | |
counter: i32 | |
} | |
struct FizzBuzzItem { | |
counter: i32, | |
items: Vec<FizzBuzz> | |
} | |
impl fmt::Display for FizzBuzzItem { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
if self.items.is_empty() { | |
write!(f, "{}", self.counter) | |
} else { | |
for item in &self.items { | |
try!(write!(f, "{}", item)); | |
} | |
Ok(()) | |
} | |
} | |
} | |
impl Iterator for FizzBuzzIter { | |
type Item = FizzBuzzItem; | |
fn next(&mut self) -> Option<FizzBuzzItem> { | |
self.counter += 1; | |
let mut items = Vec::new(); | |
if self.counter % 3 == 0 { | |
items.push(FizzBuzz::Fizz); | |
} | |
if self.counter % 5 == 0 { | |
items.push(FizzBuzz::Buzz); | |
} | |
Some(FizzBuzzItem { | |
counter: self.counter, | |
items: items | |
}) | |
} | |
} | |
impl FizzBuzzIter { | |
fn new() -> FizzBuzzIter { | |
FizzBuzzIter { | |
counter: 0i32 | |
} | |
} | |
} | |
fn main() { | |
let fizzbuzz = FizzBuzzIter::new().take(100); | |
for line in fizzbuzz { | |
println!("{}", line); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment