Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push String in String in Rust?

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.

like image 237
Damon Avatar asked Jul 27 '26 04:07

Damon


1 Answers

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"));
}
like image 117
Svetlin Zarev Avatar answered Jul 29 '26 03:07

Svetlin Zarev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!