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?
The format!
macro needs to know the actual format string at compile time. This excludes using variable and static
s, but also const
s (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);
}
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.