[solved] String append with +


#1

I want to append to strings in order to create a new string.

Let’s assume I have this:

   let h = "Hello ".to_string();
   let w = "world";

Now this works ok:

let mut hw1 = String::new();
hw1.push_str(&h);
hw1.push_str(w);
println!("{}", hw1);
println!("{}", h);

However when I try + like this:
let hw = h + w;
println!("{}", hw);
println!("{}", h);

I get: h moved here because it has type collections::string::String, which is non-copyable

Question: My understanding of h + w was that a copy of h and a copy of w will be appended to create a new String hw.
This seems to be wrong. Where do I find a documentation about the behavior of + in order to understand why this happens?

Thanks, Manfred


#2

The implementation of the Add trait for String will consume the string, so h is invalid after let hw = h + w;. I think you have to explicitly clone h if you want to use it again.

Here are the docs for the Add trait, where you can see all the standard implementations of it.


#3

Thanks. Ok, now I understand why h got invalidated. I have to admit that without your pointer to the Add trait I would never have found that it specifies the functionality of +.

Yes, clone() helps:
let hw = h.clone() + w;
println!("{}", hw);
println!("{}", h);

Thanks again, Manfred


#4

For the future: all (or, to be precise, most) of the operators are traits, so you can find them all in there :smile:


#5

Didn’t know that. Thanks for this.