How to generate a compile time error with a custom message?

⚓ Rust    📅 2026-05-18    👤 surdeus    👁️ 1      

surdeus

Hi, how do I do this?

I'm using compile time reflection in Nightly to perform checks. Once an error is detected, I want to generate a compile time error with a custom error message that includes the line number information

I tried the compile_error! macro, but it gets executed at the library level rather than when the library code is actually invoked

I tried panic! executed during compile time eval, but the error message isn't clean because it includes a lot of unnecessary stack traces for my use case. Is there a way to make the custom error message from a panic clean?

I tried combining traits + #[diagnostic::on_unimplemented] + const generic expressions to bridge the compile time reflection, traits, and generic functions. This allowed me to customize the error message according to the use case and remove complex trait technical detail messages that aren't helpful in my case because the error can't be fixed by implementing a trait (I'm preventing raw pointer returns, so the only fix is to stop returning pointers). I wanted to remove these complex messages to keep it clean (some parts still couldn't be hidden), but it was still cleaner than panic messages. The issue is that generic const expressions throw an incomplete feature warning. Previously it successfully detected pointers, but after a while I re ran it without changing any logic in the pointer detection code, and it suddenly failed, it suddently detects any types as raw pointers. When I switched back to the panic method, it worked normally again, so the generic const expression was what suddenly failed

Is there a way to generate a compile time error with a custom message that is clean and allows removing unnecessary messages?

3 posts - 2 participants

Read full topic

🏷️ Rust_feed