I can convert a u32 into String and append it to an existing string buffer like this
let mut a = String::new();
let b = 1_u32.to_string();
a.push_str(&b[..]);
But this involves allocation of a new string object in the heap.
How to push the string representation of a u32 without allocating a new String?
Should I implement an int-to-string function from scratch?
Use write! and its family:
use std::fmt::Write;
fn main() {
let mut foo = "answer ".to_string();
write!(&mut foo, "is {}.", 42).expect("This shouldn't fail");
println!("The {}", foo);
}
This prints The answer is 42., and does exactly one allocation (the explicit to_string).
(Permalink to the playground)
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