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.