55

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.

1 Answer 1

72

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Note to self: fmt::Write and io::Write are unrelated.
This is so ugly considering that we have to unwrap() the write! that never fails. The whole idea of something as simple that requires unsafe call is ludicrous. The deleted answer below is safe however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.