String literal question about macro


why this code doesn't compile ?

Thanks in advance.

You can't share your snippet with us if you just copy the link you see in your browser's address bar. If you want to link snippets from the playground, in the top right corner on the playground you find a button "Share". Click on it. In the right window you'll see a link "Permalink to the playground". Copy that link to your clipboard (there is an icon next to the text that does that for you). Then paste the link in your topic here on URLO.


Unlike most macros that take a string argument, format! isn't simply emitting code that refers to the string; it's parsing that string at macro-expansion time to decide what code to emit. This expansion happens quite early in the compilation process and so can't rely on any text outside the macro call itself— The format string has to appear directly inside format!.


I understand.

Could you suggest me a workaround to achieve the same result?

I can't tell from this code snippet what, exactly, you are trying to achieve. Can you describe what you're looking for with words?

You should usually include every piece of information in the error itself, like this:

pub enum Errors {
    ReadFileErr {
        path: String

impl Display for Errors {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ReadFileErr { path } => write!(formatter, "unable to read {} file", path),

You shouldn't (ab)use dynamic string formatting/templating for reporting errors like this. If you still insist on it, there are crates in the ecosystem for dynamic string formatting, which I'm sure you'll be able to find using a quick Google search.


I'd want to wrap those messages in an enum, to pass additional parameters for how many "{}" i can find and return the complete string.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.