6

I keep getting the error "Use of moved value".

let mut s = "s".to_string();
s = s + &s;

2 Answers 2

5

Adding a solution to Chris Morgan's answer:

let s = "s";
let mut double_s = s.to_owned(); // faster, better than to_string()
double_s = double_s + s;

You could also use

double_s.push_str(s);

instead of the last line.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a method to push_str to the start of double_s?
4

Think about what + desugars to:

s = s.add(&s);

Now this add is from the Add trait and is effectively this:

fn add(self: String, rhs: &str) -> String;

The use of self means that it is taking ownership of the string; you obviously can’t pass a reference to that as the second argument, because it isn’t yours any more.

You might think that it’d be OK doing this, but it’s not; the whole class is unsound, constituting mutable aliasing—both a mutable and immutable reference to the same thing existing at the same time. For this specific case, one way I could imagine it going wrong if permitted is if the string pushing were to reallocate the string; rhs would then conceivably be pointing to non-existent memory when it actually went to use it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.