Fizz Buzz in Rust

Published on 11 December 2021 (Updated: 11 December 2021)

Fizz Buzz in Rust

In this article, we’ll be showing you how to implement Fizz Buzz in Rust. Check it out!

How to Implement the Solution

Let’s start by looking at the complete Fizz Buzz algorithm in Rust:

fn main() {
    for number in 1..101 {
        if number % 3 == 0 && number % 5 == 0 {
            println!("FizzBuzz");
        } else if number % 3 == 0 {
            println!("Fizz");
        } else if number % 5 == 0 {
            println!("Buzz");
        } else {
            println!("{}", number);
        }
    }
}

Before we dig into the code too much, let’s take a look at the rules:

You can test for divisibility using the modulo operator %. The modulo operator divides two numbers and yields the remainder, so i modulo j is 0 if i is divisible by j. In Rust, this is written as i % j. Then, it’s a simple matter of checking whether i % 3 == 0 or i % 5 == 0.

The Loop

In the very first line, we’ll notice a for-loop:

for number in 1..101

Here, we loop through all the numbers from 1 to 100.

Control Flow

From there, we begin our testing using an if statement:

if number % 3 == 0 && number % 5 == 0 {
    println!("FizzBuzz");
} else if number % 3 == 0 {
    println!("Fizz");
} else if number % 5 == 0 {
    println!("Buzz");
} else {
    println!("{}", number);
}

How to Run the Solution

To run FizzBuzz in Rust, install the latest version of Rust. After that, create a project structure using cargo:

cargo new fizz-buzz

Copy the code from Github into ‘main.rs’. Compile and run the code from the command line using

cargo run main.rs

This will create a new ‘target’ directory containing the executable binary file.

Further Reading