Back to home

Rust Fizzbuzz

Published: Apr 13, 2019

Last updated: Apr 13, 2019

    A basic implementation of FizzBuzz in Rust.

    Writing the Code

    Execute the tests with:

    $ cargo test

    All but the first test have been ignored. After you get the first test to pass, open the tests source file which is located in the tests directory and remove the #[ignore] flag from the next test and get the tests to pass again. Each separate test is a function with #[test] flag above it. Continue, until you pass every test.

    If you wish to run all tests without editing the tests source file, use:

    $ cargo test -- --ignored

    To run a specific test, for example some_test, you can use:

    $ cargo test some_test

    If the specific test is ignored use:

    $ cargo test some_test -- --ignored

    To learn more about Rust tests refer to the [online test documentation][rust-tests]

    Make sure to read the Modules chapter if you haven't already, it will help you with organizing your files.

    Further improvements

    After you have solved the exercise, please consider using the additional utilities, described in the installation guide, to further refine your final solution.

    To format your solution, inside the solution directory use

    cargo fmt

    Cargo.toml

    Setup your Cargo.toml file to look like the following:

    [package] edition = "2019" name = "fizz_buzz" version = "0.1.0" [[test]] name = "fizz_buzz" path = "tests/fizz_buzz.rs" [dependencies] # itoa = "0.4.3"

    The test file

    In tests/fizz_buzz.rs:

    extern crate fizz_buzz; #[test] fn test_returns_string() { assert_eq!("2", fizz_buzz::run(2)); } #[test] fn test_fizz() { assert_eq!("Fizz", fizz_buzz::run(3)); } #[test] fn test_buzz() { assert_eq!("Buzz", fizz_buzz::run(5)); } #[test] fn test_fizz_buzz() { assert_eq!("FizzBuzz", fizz_buzz::run(15)); }

    FizzBuzz

    Create src/libs.rs:

    pub fn run(i: u32) -> String { if i % 15 == 0 { "FizzBuzz".to_string() } else if i % 5 == 0 { "Buzz".to_string() } else if i % 3 == 0 { "Fizz".to_string() } else { i.to_string() } }

    Run the final test

    cargo test

    Personal image

    Dennis O'Keeffe

    @dennisokeeffe92
    • Melbourne, Australia

    Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
    I am currently working on Visibuild.

    1,200+ PEOPLE ALREADY JOINED ❤️️

    Get fresh posts + news direct to your inbox.

    No spam. We only send you relevant content.

    Rust Fizzbuzz

    Introduction

    Share this post