-
-
Save ZhangHanDong/a39bc489304051a00297fbdef2a6e8b2 to your computer and use it in GitHub Desktop.
Fizzbuzz 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
#![feature(generators)] | |
#![feature(generator_trait)] | |
use std::ops::{Generator, GeneratorState}; | |
fn fizzbuzz_println(upto: u64) { | |
for i in 0..upto { | |
if i % 3 == 0 && i % 5 == 0 { | |
println!("FizzBuzz"); | |
} else if i % 3 == 0 { | |
println!("Fizz"); | |
} else if i % 5 == 0 { | |
println!("Buzz"); | |
} else { | |
println!("{}", i); | |
} | |
} | |
} | |
fn fizzbuzz_ifelse(upto: u64) -> Vec<String> { | |
let mut result: Vec<String> = Vec::new(); | |
for i in 0..upto { | |
if i % 3 == 0 && i % 5 == 0 { | |
result.push("FizzBuzz".into()); | |
} else if i % 3 == 0 { | |
result.push("Fizz".into()); | |
} else if i % 5 == 0 { | |
result.push("Buzz".into()); | |
} else { | |
result.push(i.to_string()); | |
} | |
} | |
result | |
} | |
fn fizzbuzz_vec(upto: u64) -> Vec<String> { | |
let mut result: Vec<String> = Vec::new(); | |
for i in 0..upto { | |
result.push(match (i % 3, i % 5) { | |
(0, 0) => "FizzBuzz".into(), | |
(0, _) => "Fizz".into(), | |
(_, 0) => "Buzz".into(), | |
(_, _) => i.to_string(), | |
}) | |
} | |
result | |
} | |
fn main() { | |
let fizzbuzz = |upto: u64| { | |
move || for i in 0..upto { | |
yield match (i % 3, i % 5) { | |
(0, 0) => "FizzBuzz".into(), | |
(0, _) => "Fizz".into(), | |
(_, 0) => "Buzz".into(), | |
(_, _) => i.to_string(), | |
} | |
} | |
}; | |
let mut output = fizzbuzz(100); | |
loop { | |
match output.resume() { | |
GeneratorState::Yielded(x) => println!("{}", x), | |
GeneratorState::Complete(()) => break, | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment