Fiono
Fiono

Reputation: 153

How can I format a string like this?

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?

Upvotes: 5

Views: 3142

Answers (1)

mcarton
mcarton

Reputation: 30021

The format! macro needs to know the actual format string at compile time. This excludes using variable and statics, but also consts (which are known 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.

Upvotes: 13

Related Questions