Using format!, I can create a String from a format string, but what if I already have a String that I'd like to append to? I would like to avoid allocating the second string just to copy it and throw away the allocation.
let s = "hello ".to_string(); append!(s, "{}", 5); // Doesn't exist A close equivalent in C/C++ would be snprintf.
You can use the '+' operator to append two strings to create a new string. There are various ways such as using join, format, string IO, and appending the strings with space.
AppendFormat(IFormatProvider, String, Object) Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a single argument using a specified format provider.
To concatenate String we often use StringBuilder instead of String + String , but also we can do the same with String. format which returns the formatted string by given locale, format and arguments. In performance, is String.
I see now that String implements Write, so we can use write!:
use std::fmt::Write; pub fn main() { let mut a = "hello ".to_string(); write!(a, "{}", 5).unwrap(); println!("{}", a); assert_eq!("hello 5", a); } (Playground)
It is impossible for this write! call to return an Err, at least as of Rust 1.47, so the unwrap should not cause concern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With