in Rust

A REST API in Rust and Rocket in 5 Minutes

Learn How to Create a FizzBuzz Implementation in Rust

FizzBuzz is a classical software developer interview question with the simple goal of writing an application that outputs “Fizz” for numbers divisible by 3, “Buzz” for numbers divisible by 5 and “FizzBuzz” for numbers matching both cases.

In this article, I will show you how to implement FizzBuzz using the Rust programming language and the Rocket framework.

Start by using Rust nightly and setting up a new Rust project using cargo:

rustup default nightly
cargo new fizzbuzz --bin
cd fizzbuzz
rustup update && cargo update

Edit Caro.toml and add the following dependency for Rocket:

[dependencies]
rocket = "0.4.1"

Add the following Hello World code to src/main.rs:

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use] extern crate rocket;

#[get("/<count>")]
fn index(count: isize) -> String {
    let mut output_string = "".to_string();
    for i in 1..(count+1) {
        if i % 15 == 0 { output_string = format!("{}{}", output_string, "FizzBuzz".to_string()) }
        else if i % 3 == 0 { output_string = format!("{}{}", output_string, "Fizz".to_string()) }
        else if i % 5 == 0 { output_string = format!("{}{}", output_string, "Buzz".to_string()) }
        else { output_string = format!("{}{}", output_string, i.to_string()) }
        output_string = format!("{}{}", output_string, "\n".to_string())
    }

    output_string.to_string()
}

fn main() {
    rocket::ignite().mount("/", routes![index]).launch();
}

and execute cargo run.

After a successful compilation, you should be able to see the results by navigating to http://localhost:8000/15 (where the 15 determines the range of the for loop):

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Creating a REST API using Rust is really this simple.

Write a Comment

Comment

  • Related Content by Tag