HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMajor

How can I append a formatted string to an existing String?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howexistingappendcanstringformatted

Problem

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.

Solution

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.

Context

Stack Overflow Q#28333612, score: 72

Revisions (0)

No revisions yet.