7
fn main() {
    let mut str = "string".to_string();

    // How do I push String to String?
    str.push_str(format!("{}", "new_string"));
}

So, how do I push the formatted string in str? I don't want to concatenate. Concatenation is kinda' the same thing as push but I want to know how I can push String instead.

5
  • str.push_str(&format!("{}", "new_string")); Commented Jan 18, 2022 at 10:57
  • @SvetlinZarev Thanks, that works. But how is &String allowed? Commented Jan 18, 2022 at 11:00
  • I'll write a proper answer :) Commented Jan 18, 2022 at 11:01
  • @SvetlinZarev That would be great. Thanks. Commented Jan 18, 2022 at 11:02
  • 1
    In case it's not obvious, push_str() accepts a &str rather than String because it has to copy the data anyway, so it doesn't gain anything by consuming the String it receives. And if you have an owned string, it's trivial to obtain a reference, as shown. Commented Jan 18, 2022 at 11:17

1 Answer 1

10

You cannot push String directly, but you can push a string slice - i.e. - &str. Therefore you have to get a slice from your String, which can be done in several ways:

  • By calling the string.as_str() method
  • By taking advantage by the automatic deref coercion. Because String implements Deref<Target=str>, the compiler will automatically convert the string reference (i.e. &String) to a string slice - &str.

Thus, it's enough to get reference to the formatted string in order to push it:

fn main() {
  let mut str = "string".to_string();
  str.push_str(&format!("{}", "new_string"));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Note that in this specific case str.push_str ("new_string") avoids a superfluous allocation and copy. And in case of more complicated format strings, write!(&mut str, "{}", 42) also avoids extra allocations and copies.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.