Search code examples
rustformattingstring-formatting

How can I spread a Vec<> into the arguments of format!()?


I have a Vec of strings (str or String), and I would like to use them as the arguments for format!(). If the ... syntax of JS was available, I'd do something like this:

let data = vec!["A", "B", "C"];
let result = format!("{} says hello to {} but not to {}", ...data);

Is there any alternative in Rust that would make something like this possible, and ideally without it being incredibly verbose?

I assume part of the difficulty is that the Vec might not have the right number of arguments, so it would be acceptable to me for it to panic if it has the wrong number.


Solution

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