如何将格式化字符串附加到现有字符串? [英] How can I append a formatted string to an existing String?

查看:36
本文介绍了如何将格式化字符串附加到现有字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用format!,我可以从格式字符串创建一个 String,但是如果我已经有一个想要附加到的 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

C/C++ 中的近似等效项是 snprintf.

A close equivalent in C/C++ would be snprintf.

推荐答案

我现在看到 String 实现 Write,所以我们可以使用write!:

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);
}

(游乐场)

这个 write! 调用不可能返回一个 Err,至少从 Rust 1.47 开始,所以 unwrap 不应该导致关注.

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.

这篇关于如何将格式化字符串附加到现有字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆