Reputation: 611
Consider below code:
fn main(){
let mut s = "Hi".to_string();
s.push_str(&" foo".to_string());
println!("{}",s);
}
We send reference of foo
(i.e, a String not str) in push_str
. But, we are not storing foo
in any variable and just sending the reference.
Where does the value foo
live for the reference to be valid inside of push_str
.
As I'm just borrowing foo
, how can I refer to foo
(as a reference) later in my code i.e, after println
?
Upvotes: 0
Views: 50
Reputation: 70397
Rust temporaries exist until the end of the current expression, and they can even be extended if necessary. The Rust compiler effectively creates a temporary variable for that temporary that you never see. This
s.push_str(&" foo".to_string());
is semantically equivalent to
{
let tmp = " foo".to_string();
s.push_str(&tmp);
}
Upvotes: 2