cur*_*nii 5 formatting string-formatting rust
我有一个Vec字符串(str或String),我想将它们用作 的参数format!()。如果...JS 的语法可用,我会这样做:
let data = vec!["A", "B", "C"];
let result = format!("{} says hello to {} but not to {}", ...data);
Run Code Online (Sandbox Code Playgroud)
Rust 中是否有任何替代方案可以使类似的事情成为可能,并且理想情况下不会变得非常冗长?
我认为部分困难在于Vec参数的数量可能不正确,因此如果参数数量错误,我可以接受它会出现恐慌。
The dyn-fmt crate looks like exactly what I need. It specifies a trait which adds a format() method to strings, which takes an Iterator. Any extra arguments are ignored, and missing ones are replaced with an empty string, so it won't panic. If you don't need format!()'s various formatting options, then it looks like a really good solid option.
use dyn_fmt::AsStrFormatExt;
let data = vec!["A", "B", "C"];
let result = "{} says hello to {} but not to {}".format(data);
assert_eq!(result, "A says hello to B but not to C");
Run Code Online (Sandbox Code Playgroud)