2
votes

The following is obviously not working:

fn main() {
    for i in range(1i, 101) {
        println!("{}", if i % 15 == 0 {
            "Fizzbuzz"
        } else if i % 5 == 0 {
            "Buzz"
        } else if i % 3 == 0 {
            "Fizz"
        } else {
            i
        });
    };
}

It can be made work like this:

fn main() {
    for i in range(1i, 101) {
       println!("{}", 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()
        });
    }
}

But what is the most elegant (probably idiomatic) way to make it work in a similar fashion using if/else with expressions?

1
What do you mean "using implicit returns"? There are no explicit returns in your example code. - Shepmaster
Yeah sorry, wrong term. I meant using the condition as expression to "return" the result as a value. And than you for the link! - OderWat

1 Answers

5
votes

The comprehensive exploration of FizzBuzz uses a now deprecated struct called MaybeOwned. Here's the updated version, with the delightfully-named CowString:

use std::borrow::Cow;

fn main() {
    for i in 1..10 {
        println!("{}", if i % 15 == 0 {
            Cow::Borrowed("Fizzbuzz")
        } else if i % 5 == 0 {
            Cow::Borrowed("Buzz")
        } else if i % 3 == 0 {
            Cow::Borrowed("Fizz")
        } else {
            Cow::Owned(i.to_string())
        });
    };
}

However, you should read that full blog post for maximal education!