Formatting const string with named parameters

Given a constant string with named parameters, like:

const XYZ: &str = "{foo}{bar}";

I'd like to do something like:

format!(XYZ, foo = "foo", bar = "bar");

I know this is possible by making XYZ a macro instead of a const string but any better solution?

error: format argument must be a string literal
 --> src/main.rs:3:9
  |
3 | format!(XYZ, foo = "foo", bar = "bar");
  |         ^^^
  |
help: you might be missing a string literal to format with
  |
3 | format!("{} {} {}", XYZ, foo = "foo", bar = "bar");
  |         +++++++++++

As the error points out, the first argument in format! must be a string literal.

A string literal is a sequence of any Unicode characters enclosed within two U+0022 (double-quote) characters, with the exception of U+0022 itself, which must be escaped by a preceding U+005C character (\ ).

That means you should write "xxx" in there. (Or utilize expansion of some compiler macro in very rare cases, but not for yours here.)

A value from a const item is not a string literal.

So there two ways for your code:

1 Like