Macro static_assertions::const_assert
source · macro_rules! const_assert {
($($xs:tt)+) => { ... };
}
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++.
Alternatives
There also exists const_assert_eq
for
validating whether a sequence of expressions are equal to one another.
Examples
On stable Rust, using the macro requires a unique “label” when used in a module scope:
const_assert!(meaning_of_life; 42 == !!42);
The labeling limitation is not necessary if
compiling on nightly Rust with the nightly
feature enabled:
ⓘ
#![feature(underscore_const_names)]
const FIVE: usize = 5;
const_assert!(FIVE * FIVE == 25);
fn main() {
const_assert!(2 + 2 == 4);
const_assert!(FIVE - FIVE == 0);
}
Some expressions are blatantly false:
ⓘ
const_assert!(1 >= 2);