How can I store a format string template outside of my source code?

Viewed 1257

When translating, messages can be in different languages and have format parameters. I want to be able to do this where the template can be stored in a file:

static PATTERN: &'static str = r"Hello {inner};";

/// in some implementation

fn any_method(&self) -> String {
    format!(PATTERN, inner = "world");
}
2 Answers

That's not possible. Format strings must be actual literal strings.

The next best approach would be some kind of dynamic string format library. Or, failing that, you could always use str::replace if your needs aren't too complex.

This is trivial to do using the include_str macro that has been available in the standard library since version 1.0.0. The following example was tested with rustc 1.58.1:

  • Contents of src/main.rs:

    println!(include_str!("src/hello-world.tmpl"), "world");
    
  • Contents of src/hello-world.tmpl

    Hello {inner}
    

This works because include_str injects the contents of the template file as a string literal before println, format, and friends have a chance to evaluate their arguments. This approach only works when the format template you want to include is available during macro expansion - like it is in your example. If it's not, then you should consider other options like the ones suggested by @DK.

As an added bonus: You can also define format strings in source code locations other than the site where they are used by defining them as macros.

Related