Skip to main content

build_assert

Macro build_assert 

Source
macro_rules! build_assert {
    ($cond:expr $(,)?) => { ... };
    ($cond:expr, $msg:expr) => { ... };
}
Expand description

Asserts that a boolean expression is true at compile time.

If the condition is evaluated to false in const context, build_assert! will panic. If the compiler or optimizer cannot guarantee the condition will be evaluated to true, a build error will be triggered.

When a condition depends on a function argument, the function must be annotated with #[inline(always)]. Without this attribute, the compiler may choose to not inline the function, preventing it from optimizing out the error path.

If the assertion condition does not depend on any variables or generics, you should use static_assert!. If the assertion condition does not depend on variables, but does depend on generics, you should use const_assert!. See the module documentation.

ยงExamples

#[inline(always)] // Important.
fn bar(n: usize) {
    build_assert!(n > 1);
}

fn foo() {
    bar(2);
}

#[inline(always)] // Important.
const fn const_bar(n: usize) {
    build_assert!(n > 1);
}

const _: () = const_bar(2);