Skip to content

Instantly share code, notes, and snippets.

@neiesc
Created January 31, 2025 18:20
Show Gist options
  • Save neiesc/29849051990942959a920d95c267b93a to your computer and use it in GitHub Desktop.
Save neiesc/29849051990942959a920d95c267b93a to your computer and use it in GitHub Desktop.
FizzBuzz in rust πŸ¦€
use clap::Parser;
use std::error::Error;
#[derive(Debug, Parser)]
struct Cli {
#[structopt(short = 'n')]
num: usize
}
fn main() -> Result<(), Box<dyn Error>> {
let args = Cli::parse();
for i in 1..(args.num + 1) {
println!("{}", fizz_buzz_print(i));
}
Ok(())
}
fn fizz_buzz_print(i: usize) -> String {
if i % 3 == 0 && i % 5 == 0 {
"FizzBuzz".to_string()
} else if i % 3 == 0 {
"Fizz".to_string()
} else if i % 5 == 0 {
"Buzz".to_string()
} else {
i.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn result_when_zero_pass() {
let result = fizz_buzz_print(0);
assert_eq!(result, "FizzBuzz");
}
#[test]
fn result_when_one_pass() {
let result = fizz_buzz_print(1);
assert_eq!(result, "1");
}
#[test]
fn result_when_two_pass() {
let result = fizz_buzz_print(2);
assert_eq!(result, "2");
}
#[test]
fn result_when_three_pass() {
let result = fizz_buzz_print(3);
assert_eq!(result, "Fizz");
}
#[test]
fn result_when_for_pass() {
let result = fizz_buzz_print(4);
assert_eq!(result, "4");
}
#[test]
fn result_when_five_pass() {
let result = fizz_buzz_print(5);
assert_eq!(result, "Buzz");
}
#[test]
fn result_when_14_pass() {
let result = fizz_buzz_print(14);
assert_eq!(result, "14");
}
#[test]
fn result_when_15_pass() {
let result = fizz_buzz_print(15);
assert_eq!(result, "FizzBuzz");
}
#[test]
fn result_when_16_pass() {
let result = fizz_buzz_print(16);
assert_eq!(result, "16");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment