Our weekly lunchtime coding dojo is starting back up again and this time our junior engineers wanted to try a new language. We decided on rust and used cyber-dojo to kick off with a let's see if we can get anthing working session using FizzBuzz test-first as our objective.

Lots of the original floundering was helped by the wonderful documentation and the diagnostics emitted by the compiler. Chief among the confusions was re-aquainting ourselves with the memory management model and the idea of ownership. Coming from a managed language like C#, the distinction between string literals and String objects was initially confusing but the diagnostics really did help with their suggestions on what we should be doing.

We also liked the declarations for parameters and return types for functions which are very like the Elm model or the way that UML handles documentation of types - value : type.

Here's the less than elegant but working function followed by the tests we used to drive it.


#![cfg_attr(feature = "strict", deny(warnings))]

pub fn fizz_buzz(x: i32) -> String {
    let mut word = String::new();
    if x % 3 == 0 || x % 5 == 0 {
        if x % 3 == 0 {
            word.push_str("fizz");
        }
        if x % 5 == 0 {
            word.push_str("buzz");
        }
    } else {
        word.push_str(&x.to_string());
    }
    return word;
}

#[test]
fn one_returns_number_as_string() {
    assert_eq!("1", fizz_buzz(1));
}

#[test]
fn three_returns_fizz() {
    assert_eq!("fizz", fizz_buzz(3));
}

#[test]
fn five_returns_buzz() {
    assert_eq!("buzz", fizz_buzz(5));
}

#[test]
fn fifteen_returns_fizzbuzz() {
    assert_eq!("fizzbuzz", fizz_buzz(15));
}