-3

This is what I'm trying to do:

format!(match x { 0 => "Hello, {}", 1 => "Bye, {}" }, name);

It doesn't compile. What is the solution?

yegor256
  • 102,010
  • 123
  • 446
  • 597
  • 2
    The solution is to have format inside match, not the other way around. Format strings are required to be literals. – Ivan C Feb 03 '22 at 15:32

2 Answers2

3

The format! macro needs a fixed string literal as a first parameter (the format string). Macros are translated into "normal" code during the compilation process, so the format string must be parsed and analyzed at that very phase, not at runtime. That's why it's not possible to have a runtime expression as a format string.

You can do something like this:

let s = match x {
    0 => format!("Hello, {x}"),
    1 => format!("Bye, {x}"),
    _ => panic!("Unexpected value: {x}"),
};
at54321
  • 8,726
  • 26
  • 46
1
let greeting = match x {
    0 => format!("Hello, {}", name),
    1 => format!("Bye, {}", name),
    _ => panic!(),
};
Riwen
  • 4,734
  • 2
  • 19
  • 31