【问题标题】:How can I append a formatted string to an existing String?如何将格式化字符串附加到现有字符串?
【发布时间】:2015-04-04 16:43:49
【问题描述】:

使用format!,我可以从格式字符串创建一个String,但是如果我已经有一个我想附加到的String,该怎么办?我想避免分配第二个字符串只是为了复制它并丢弃分配。

let s = "hello ".to_string();
append!(s, "{}", 5); // Doesn't exist

C/C++ 中的近似等价物是snprintf

【问题讨论】:

    标签: string-formatting rust


    【解决方案1】:

    我现在看到String implements Write,所以我们可以使用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)

    is impossible for this write! call to return an Err,至少从 Rust 1.47 开始,所以 unwrap 不应该引起关注。

    【讨论】:

      猜你喜欢
      • 2019-07-19
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多