I have the following code that works fine:
fn main() {
let mut example = String::new();
if 1 + 1 == 2 {
example += &"string".to_string()
} else {
example += &'c'.to_string()
};
println!("{}", example);
}
When I change the code to this:
fn main() {
let mut example = String::new();
example += if 1 + 1 == 2 {
&"string".to_string()
} else {
&'c'.to_string()
};
println!("{}", example);
}
I get the following error:
error[E0597]: borrowed value does not live long enough
--> src/main.rs:5:10
|
5 | &"string".to_string()
| ^^^^^^^^^^^^^^^^^^^^ temporary value does not live long enough
6 | } else {
| - temporary value dropped here while still borrowed
7 | &'c'.to_string()
8 | };
| - temporary value needs to live until here
error[E0597]: borrowed value does not live long enough
--> src/main.rs:7:10
|
7 | &'c'.to_string()
| ^^^^^^^^^^^^^^^ temporary value does not live long enough
8 | };
| - temporary value dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
This makes no sense to me as both snippets seem identical. Why doesn't the second snippet work?
&"string".to_string().