user2417339
user2417339

Reputation:

How can I concatenate something to the front of a string?

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

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

Upvotes: 6

Views: 7711

Answers (2)

llogiq
llogiq

Reputation: 14511

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.

Upvotes: 5

Chris Morgan
Chris Morgan

Reputation: 90712

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.

Upvotes: 4

Related Questions