如何有效地将可显示项目推入字符串? [英] How to efficiently push displayable item into String?

查看:26
本文介绍了如何有效地将可显示项目推入字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看这个例子:

fn concat<T: std::fmt::Display>(s: &mut String, thing: T) {
    // TODO
}

fn main() {
    let mut s = "Hello ".into();
    concat(&mut s, 42);

    assert_eq!(&s, "Hello 42");
}

我知道我可以使用这个:

I know that I can use this:

s.push_str(&format!("{}", thing))

但这并不是最有效的,因为 format! 分配了一个不必要的 String.

but this is not the most efficient, because format! allocate a String that is not necessary.

最有效的方法是将可显示项的字符串表示直接写入String 缓冲区.如何做到这一点?

The most efficient is to write directly the string representation of the displayable item into the String buffer. How to do this?

推荐答案

有多个格式化宏,在您的情况下,您需要 write! 宏:

There are multiple formatting macros, and in your case you want the write! macro:

use std::fmt::{Display, Write};

fn concat<T: Display>(s: &mut String, thing: &T) {
    write!(s, "{}", thing).unwrap();
}

fn main() {
    let mut s = "Hello ".into();
    concat(&mut s, &42);

    assert_eq!(&s, "Hello 42");
}

任何实现 Write 特性之一(以及 String 实现)的东西都是 write! 的有效目标.

Anything that implements one of the Write trait (and String does) is a valid target for write!.

注意:实际上任何实现了 write_fmt 方法的东西,因为宏不太关心语义;这就是 fmt::Writeio::Write 工作的原因.

Note: actually anything that implements a write_fmt method, as macro don't care much about semantics; which is why either fmt::Write or io::Write work.

这篇关于如何有效地将可显示项目推入字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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