static-assertions icon indicating copy to clipboard operation
static-assertions copied to clipboard

Consider using `const_panic` in the future.

Open konsumlamm opened this issue 4 years ago • 3 comments

Tracking issue for const_panic: https://github.com/rust-lang/rust/issues/51999.

Once this gets stabilized, it would be allowed to panic in a const context, so macros like const_assert could be implemented like this:

macro_rules! const_assert {
    ($x:expr $(,)?) => {
        const _: () = if $x { () } else { panic!("static assertion failed") };
    };
}

konsumlamm avatar Aug 19 '21 12:08 konsumlamm

It's stabilized today.

andylizi avatar Oct 05 '21 05:10 andylizi

Not only is it stable in the nightly channel, you can define a const_assert macro like this:

macro_rules! const_assert {
    ($x:expr $(,)?) => {
        const _: () = assert!($x);
    };
}

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=e32154ec03b111a11e1bef66caa88cf0

const_assert!(2+2==5);
error[E0080]: evaluation of constant value failed
 --> src/lib.rs:3:23
  |
3 |         const _: () = assert!($x);
  |                       ^^^^^^^^^^^ the evaluated program panicked at 'assertion failed: 2 + 2 == 5', src/lib.rs:7:1
...
7 | const_assert!(2+2==5);
  | ---------------------- in this macro invocation
  |
  = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info)

rodrimati1992 avatar Oct 06 '21 07:10 rodrimati1992

FWIW, const_panic just landed in stable version 1.57.0, released today.

ian-h-chamberlain avatar Dec 03 '21 04:12 ian-h-chamberlain