What's the ideomatic way to replace a string?

If I have a String, and I want to reuse it, currently I do

// s is a mut String
s.truncate();
s.push_str(a_str);

Is this the best/most efficient way to do it? I also looked at replace_range(.., a_str).

EDIT: s.truncate() is incorrect, it should say s.truncate(0).

s.clear();
s.push_str(a_str);

is what I’d use. replace_range is more flexible but I’d expect it to run slower than the above.

3 Likes

This looks like the exact use case of clone_into(). Unfortunately, people aren’t happy with the way this method looks and it’ll need a champion to get stabilized.

2 Likes