static-assertions
static-assertions copied to clipboard
Consider using `const_panic` in the future.
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") };
};
}
It's stabilized today.
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)
FWIW, const_panic just landed in stable version 1.57.0, released today.