This is my code:
fn main() {
fn fizz_buzz<'a>(i: i32) -> &'a str {
if i % 15 == 0 {
"FizzBuzz"
} else if i % 5 == 0 {
"Buzz"
} else if i % 3 == 0 {
"Fizz"
} else {
&i.to_string()
}
}
for i in 1..101 {
println!("{}" , fizz_buzz(i));
}
}
The compiler gives me this error:
error[E0515]: cannot return reference to temporary value
--> src/main.rs:11:9
|
11 | &i.to_string()
| ^-------------
| ||
| |temporary value created here
| returns a reference to data owned by the current function
For more information about this error, try `rustc --explain E0515`.
error: could not compile `playground` due to previous error
I tried a static lifetime.
Your function will correctly give back a reference to the strings "FizzBuzz," "Buzz," and "Fizz" (whose lifetimes are static since they're compiled in) however the
&i.to_string()does not have that same property. Let's look at the lifetime in detail:When
fizz_buzzis called,iis copied (because i32 implements the Copy trait) and given to it. In that else block, however, we do the following:StringStringhowever, the lifetime of that
Stringis only as long as the fizz_buzz function call! Since we need to use its reference outside of that scope, Rust calls foul.There are a couple ways to make this type safe. You could return owned values rather than references:
Though this will end up creating a lot of identical objects on the heap (consider how many "Fizz"es there are, for instance)
The other option that I'd prefer is to have fizz_buzz return an Option<&str>, and have the calling scope handle the case when fizz_buzz gives None.
As @RobinZigmond points out in the comments, you could also return an enum and implement Display for it.