[solved] String append with +

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();
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

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.

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

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

1 Like

Didn't know that. Thanks for this.