macro_rules! const_assert {
    ($x:expr $(,)?) => { ... };
Expand description

Asserts that constant expressions evaluate to true.

Constant expressions can be ensured to have certain properties via this macro If the expression evaluates to false, the file will fail to compile. This is synonymous to static_assert in C++.


There also exists const_assert_eq for validating whether a sequence of expressions are equal to one another.


A common use case is to guarantee properties about a constant value that’s generated via meta-programming.

const VALUE: i32 = // ...

const_assert!(VALUE >= 2);

Inputs are type-checked as booleans:


Despite this being a macro, we see this produces a type error:

  | const_assert!(!0);
  |               ^^ expected bool, found integral variable
  = note: expected type `bool`
             found type `{integer}`

The following fails to compile because multiplying by 5 does not have an identity property:

const_assert!(5 * 5 == 5);