Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I use match inside format!() as a formatting string?

This is what I’m trying to do:

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

It doesn’t compile. What is the solution?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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}"),
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading