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

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 15:27:35

I see now that String implements Write, so we can just use write!:

use std::fmt::Write;

pub fn main() {
    let mut a = "hello ".to_string();
    write!(&mut 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.23, so the unwrap should not cause concern.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!