I am new to Rust. While trying to concatenate string literals and integers, I was given many errors because of the "to_string" function. After that realized that I needed to put a reference/ampersand (&) in front of an integer. However, I cannot understand why. Can you explain why I need to put a reference sign in front of an integer for the to_string function? I wrote an example code below.
fn main() {
let number = 42;
let text = "The answer is";
let result = text.to_owned() + " " + &number.to_string();
println!("{}", result);
}
Because the +
operator for strings take String
and &str
and not String
and String
, as that is what the std::ops::Add
implementation takes.
This is because to concatenate a string efficiently, you need one of the strings to be owned, so we can reuse its buffer and possibly avoid an allocation, but you don't need the other string to be owned, a reference is enough. Technically, there is no reason why impl Add<String> for &str
can't be provided too, it just doesn't exist.