How can I use a dynamic format string with the format! macro?

前端 未结 2 1597
礼貌的吻别
礼貌的吻别 2021-01-03 20:23

I want to use the format! macro with a String as first argument, but because the macro expects a string literal, I am not able pass anything differ

相关标签:
2条回答
  • 2021-01-03 20:51

    Check out the strfmt library, it is the closest I've found to do dynamic string formatting.

    0 讨论(0)
  • 2021-01-03 20:52

    Short answer: it cannot be done.


    Long answer: the format! macro (and its derivatives) requires a string literal, that is a string known at compilation-time. In exchange for this requirement, if the arguments provided do not match the format, a compilation error is raised.


    What you are looking for is known as a template engine. A non-exhaustive list of Rust template engines in no particular order:

    • Handlebars
    • Rustache
    • Maud
    • Horrorshow
    • fomat-macros
    • ...

    Template engines have different characteristics, and notably differ by the degree of validation occurring at compile-time or run-time and their flexibility (I seem to recall that Maud was very HTML-centric, for example). It's up to you to find the one most fitting for your use case.

    0 讨论(0)
提交回复
热议问题