How to efficiently push displayable item into String? [duplicate]

折月煮酒 提交于 2021-02-16 18:54:25

问题


See this example:

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

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

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


回答1:


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

Anything that implements one of the Write trait (and String does) is a valid target for 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.



来源:https://stackoverflow.com/questions/48790708/how-to-efficiently-push-displayable-item-into-string

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