Macro static_assertions::const_assert [−][src]
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
Some expressions are blatantly false:
ⓘ
const_assert!(1 >= 2);
Inputs are type-checked as booleans:
ⓘ
const_assert!(!0);
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}`
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); }