Created
November 2, 2017 13:48
-
-
Save nvzqz/a981e147c536884c974014311fdd0d39 to your computer and use it in GitHub Desktop.
Constant assertions in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This gist is used as an example within https://nikolaivazquez.com/posts/programming/rust-static-assertions/