I only just started learning rust and don't quite understand the referencing system that rust uses yet. In the following function, I am trying to write code for FizzBuzz that assigns result a &str depending on the lowest common multiple of a u32 in a range.
fn fizzbuzz(last_num: u32) {
for i in 1..last_num+1 {
let result = if i % 15 == 0 {
"FizzBuzz"
} else if i % 3 == 0 {
"Fizz"
} else if i % 5 == 0 {
"Buzz"
} else {
&i.to_string()[..]
};
println!("{}", result);
}
}
in my else clause, I get the following error:
11 | } else if i % 5 == 0 {
| ________________-
12 | | "Buzz"
13 | | } else {
14 | | &i.to_string()[..]
| | ^^^^^^^^^^^^^ creates a temporary which is freed while still in use
15 | | };
| | -
| | |
| |_________temporary value is freed at the end of this statement
| borrow later used here
From what I understand so far about rust, this shouldn't be an issue because the &i reference is being used before the end of the scope where i is freed from memory.
What exactly am I doing wrong, and what is the fix?