Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 718
Shepmaster Avatar asked Feb 04 '15 23:02

Shepmaster


People also ask

How do I append to a string?

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.

What is AppendFormat?

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.

Does string format use StringBuilder?

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.


1 Answers

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.

like image 200
Shepmaster Avatar answered Sep 22 '22 04:09

Shepmaster