3
static TEST: &str = "test: {}";

fn main() {
    let string = format!(TEST, "OK");
    println!("{}", string);
}

I want to construct the string "test: OK", but this doesn't work. How can I do it?

Fiono
  • 133
  • 4
  • 1
    The question was closed a bit prematurely, as this specific example can be solved as per my answer since the format is string is know at compile time, while the linked duplicated is really about dynamic format strings. – mcarton Apr 24 '20 at 10:42

1 Answers1

10

The format! macro needs to know the actual format string at compile time. This excludes using variable and statics, but also consts (which are know at compile time, but at a later compilation phase than macro expansion).

However in this specific case you can solve your problem by emulating a variable with another macro:

macro_rules! test_fmt_str {
    () => {
        "test: {}"
    }
}

fn main() {
    let string = format!(test_fmt_str!(), "OK");
    println!("{}", string);
}

(Permalink to the playground)

If your format string isn't actually know at compile and can't be used in a macro like this, then you need to use a dynamic template engine.

mcarton
  • 27,633
  • 5
  • 85
  • 95