Skip to content

Instantly share code, notes, and snippets.

@nvzqz
Created November 2, 2017 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nvzqz/a981e147c536884c974014311fdd0d39 to your computer and use it in GitHub Desktop.
Save nvzqz/a981e147c536884c974014311fdd0d39 to your computer and use it in GitHub Desktop.
Constant assertions in Rust
macro_rules! const_assert {
($($condition:expr),+ $(,)*) => {
let _ = [(); 0 - !($($condition)&&+) as usize];
};
($label:ident; $($rest:tt)+) => {
#[allow(non_snake_case, dead_code)]
fn $label() {
const_assert!($($rest)+);
}
};
}
const_assert! { simple_math;
2 * 2 == 2 + 2,
5 * 2 == 10,
}
fn main() {
// Change me to `false`
const ASSERTION: bool = true;
const_assert!(ASSERTION);
const_assert!(2 + 2 == 4);
const_assert!(5 * 5 == 25);
}
@nvzqz
Copy link
Author

nvzqz commented Nov 9, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment