How to write a panic! like macro in Rust?

前端 未结 1 652
余生分开走
余生分开走 2021-01-29 09:16

For fatal error handling, I\'m using the panic! macro, but I would prefer to have a macro that did not print the file/line information, only the error message.

相关标签:
1条回答
  • 2021-01-29 09:49

    First, if I put the exit() call in, as I have on the last line, I get syntax errors when trying to call it.

    That is because a macro should expand to a single item, and here it expands to two. You can simply wrap the invocation in a block {} and it'll just work... once you qualify the call to exit.

    ({ print!(concat!($fmt, "\n"), $($arg)*); std::process::exit(-1) });
    

    If I remove the exit(), I don't get complaints about the macro, but this code fails to compile. Whereas it does compile when die is replaced with panic. I assume there is some magic about panic which tells the compiler that it never returns?

    It's not so much magic as the ! type. The panic and exit functions both return ! which is a type with no value: it cannot ever be constructed.

    This is sufficient for the compiler to know that those functions will never return (they diverge), so from the point of view of type-checking, ! is considered a subtype of all types and does not cause issues.

    0 讨论(0)
提交回复
热议问题