Stabilization of panic! in const context brings us static_assert possibility

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.

4 Likes

This was absolutely one of the use cases envisioned during stabilization!

4 Likes

Now I feel compelled to create a macro for something like

#[repr(C, packed)]
#[expected_size(512)]
struct MyStruct{
 ...
}
2 Likes

... which I did right now. See my pakr-assert-size topic.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.