The #1 of 1.57 stable
brings us panic!
in const contexts.
Lo and behold:
#[macro_export]
macro_rules! static_assert {
($assert:expr, $message:literal) => {
const _: () = assert!($assert, $message);
};
}
Later in code, for example:
static_assert!(
mem::size_of::<MyStruct>() == 512,
"MyStruct size not 512 bytes"
);
Damn useful if you interop with C libraries and hand-create #[repr(C, packed)]
and #[repr(C)]
structs and you know the expected size in advance.
This would throw a compile-time error, if the size is not what is expected.
error[E0080]: evaluation of constant value failed
--> my_test.rs:94:1
|
94 | / static_assert!(
95 | | mem::size_of::<MyStruct>() == 512,
96 | | "MyStruct size not 512"
97 | | );
| |_^ the evaluated program panicked at 'MyStruct size not 512', my_test.rs:94:1
|
= note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info)
Hope it helps someone, enjoy.