0
\$\begingroup\$

I want to make fizzbuzz method return the resolved value and then pass it to println!. Been having quite a problem with &str vs String. Wanted to use &str as return value as it's immutable so I tought it fit nicely though I couldn't get it right.

Here is my String impl:

fn main() {
    let ss = "FizzBuzz";
    for i in 1..100 {
        println!("{}", fizzbuzz(i))
    }
}

fn fizzbuzz(value: i32) -> String {
    return match (value % 3, value % 5) {
        (0, 0) => "FizzBuzz".into(),
        (0, _) => "Fizz".into(),
        (_, 0) => "Buzz".into(),
        (_, _) => value.to_string()
    };
}

Is there a way to make it simpler without calling straight println!("Fizzbuzz") and so on?

\$\endgroup\$
6
\$\begingroup\$

Wanted to use &str as return value as it's immutable

That is not possible because the function may produce a new, owned string out of value, in this line:

    (_, _) => value.to_string()

All other match arms could return a &'static str since they are string literals, but the output of this one is a String. And the fact that you will not mutate the string doesn't change things here, because a new string needs to be constructed anyway.

For cases where a value may either borrow or own the data, you may consider using a Cow.

fn fizzbuzz(value: i32) -> Cow<'static, str> {
    match (value % 3, value % 5) {
        (0, 0) => "FizzBuzz".into(),
        (0, _) => "Fizz".into(),
        (_, 0) => "Buzz".into(),
        (_, _) => value.to_string().into()
    }
}

This function will be slightly more efficient memory-wise: the first three guards will return a borrowed static string (Cow::Borrowed), whereas the last one will own a string (Cow::Owned). The .into() calls are necessary for the conversion from the base type (either &str or String) to a Cow.

Other issues:

  • return statements at the end of a function are redundant. You can just write the expression without a semi-colon at the end.
  • you are not using the variable ss in main.
  • although entirely subjective, u32 may be used instead of i32 when negative numbers are never considered in your program logic.

Is there a way to make it simpler without calling straight println!("Fizzbuzz") and so on?

Other than the given suggestions, I'm afraid that the given code appears simple and readable enough. That function does not hold a very complex logic.

| improve this answer | |
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.