This is what I'm trying to do:
format!(match x { 0 => "Hello, {}", 1 => "Bye, {}" }, name);
It doesn't compile. What is the solution?
This is what I'm trying to do:
format!(match x { 0 => "Hello, {}", 1 => "Bye, {}" }, name);
It doesn't compile. What is the solution?
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}"),
};
let greeting = match x {
0 => format!("Hello, {}", name),
1 => format!("Bye, {}", name),
_ => panic!(),
};