15

I'm trying to define a constant format string that is used in a number of places with the format! macro.

I've tried something like:

const FORMAT_A: &'static str = "a: {}";
static FORMAT_B: &'static str = "b: {}";

fn main() {
    format!(FORMAT_A, "a");
    format!(FORMAT_B, "b");
}

However, this fails to compile with:

error: format argument must be a string literal.
 --> src/main.rs:5:13
  |
5 |     format!(FORMAT_A, "a");
  |             ^^^^^^^^

error: format argument must be a string literal.
 --> src/main.rs:6:13
  |
6 |     format!(FORMAT_B, "b");
  |             ^^^^^^^^

Is there another way I should be defining a constant string literal to use with format!?

Dave Challis
  • 3,525
  • 2
  • 37
  • 65
  • https://stackoverflow.com/questions/39349286/can-macros-match-against-constant-arguments-instead-of-literals – Ry- Oct 17 '17 at 10:45
  • 8
    But you can define them as macros: `macro_rules! FORMAT_A { () => { "a: {}" }; }` and `format!(FORMAT_A!(), "a")`. – Ry- Oct 17 '17 at 10:49
  • 1
    Also related: [println! error: format argument must be a string literal](https://stackoverflow.com/questions/27734708/println-error-format-argument-must-be-a-string-literal). – ljedrz Oct 17 '17 at 10:49
  • Thanks, tried searching for similar questions, but didn't include the word "macro" so nothing useful came up (I thought from error messages that I wasn't declaring string literals correctly). – Dave Challis Oct 17 '17 at 10:57
  • @DaveChallis One of the other questions had a link to this but I think it's worth repeating here: [meaning of the term "literal"](https://en.wikipedia.org/wiki/Literal_%28computer_programming%29) – trent Oct 17 '17 at 15:39
  • 3
    simple things like this should be implemented in the language :( using macros for it is just silly – Vladimir Demirev Feb 12 '20 at 20:13
  • For some reason, this should be allowed by the compiler as the string literals are defined as compile time constants!!! – jaques-sam May 22 '23 at 07:56

0 Answers0