How to push String in String in Rust?
Asked Answered
A

1

6
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.

Aliciaalick answered 18/1, 2022 at 10:54 Comment(5)
str.push_str(&format!("{}", "new_string"));Jessabell
@SvetlinZarev Thanks, that works. But how is &String allowed?Aliciaalick
I'll write a proper answer :)Jessabell
@SvetlinZarev That would be great. Thanks.Aliciaalick
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.Dishabille
J
9

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"));
}
Jessabell answered 18/1, 2022 at 11:4 Comment(1)
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.Milfordmilhaud

© 2022 - 2024 — McMap. All rights reserved.