# Simplest way to write “FizzBuzz” in Rust

Can you write an a simpler Rust fizzbuzz program than I have? Use my output or the spec:

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

to write your program. I want to see if it's possible to write an even simpler program.

fn main() {
for i in 1..102 {
match i {
i if (i % 15 == 0) => { println!("{:?}", "FizzBuzz") },
i if (i % 3 == 0) => { println!("{:?}", "Fizz") },
i if (i % 5 == 0) => { println!("{:?}", "Buzz") },
_ => { println!("{:?}", i) },
}
}
}

• – Shepmaster May 4 '16 at 14:04
• @Shepmaster interesting, thanks! It might answer my question. – user May 4 '16 at 14:23

I think that match is better, you just do not know how to cook it ;)

fn main() {
for i in 1..102 {
match (i%3, i%5) {
(0, 0) => println!("FizzBuzz"),
(0, _) => println!("Fizz"),
(_, 0) => println!("Buzz"),
(_, _) => println!("{}", i)
}
}
}

• +1 This is great because it avoids having the 15, which is really an artifact of the problem. Minor nits: Rust places spaces between binary operators and has trailing commas on the last match arm. I might also have put the == 0 in the match statement and use booleans in the arms. – Shepmaster May 4 '16 at 16:27
• @passer come to think of it, it's an excellent example of how to use match and patterns. – user May 17 '16 at 12:04
1. I don't think the match adds a lot here (and I love using match). I'd just use chained if-else blocks.

2. There's no need to format a string literal; just put that string in the println! call directly.

3. Use {} for user-facing output; {:?} is for developer-facing output.

4. There's no need for parenthesis around the if condition. Standalone ifs actually have a lint to remove those parenthesis.

fn main() {
for i in 1..102 {
if i % 15 == 0 { println!("FizzBuzz") }
else if i % 3 == 0 { println!("Fizz") }
else if i % 5 == 0 { println!("Buzz") }
else { println!("{}", i) }
}
}

• Neat. thanks. you right. I like that the outer most curly braces are all in alignment. – user May 4 '16 at 14:50

Depending on what you mean by 'simple'...

fn main() {
for i in 1 .. 101 {
let s = check(i,3,"Fizz").to_string() + check(i,5,"Buzz");
println!("{}",if s == "" { i.to_string() } else { s });
}
}

fn check(n: i8, d: i8, s: &str) -> &str
{
if n % d == 0 { s } else { "" }
}

• 1 This formatting (indentation, brace placement, spacing around symbols) is not idiomatic Rust. Please check out rustfmt. 2 I dislike the embedded if — less lines does not a simpler program make. 3 This has many unneeded memory allocations from the to_string. 4 check is a poor name. – Shepmaster May 12 '17 at 14:40