-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature Request static asserts #2790
Comments
It is definitely useful! Check out the static_assertions crate, which offers similar macros for compile-time asserts. It might be worth seeing if there is anything left to explore in that crate before putting the macros into core. The Rust Internals forum is often a good place for discussions like these. cc @nvzqz |
@memoryruins it looks like you're not the only one this week suggesting this: rust-lang/rust#61347 (comment). |
rust-lang/rust#51999 allows panicking in constants, and rust-lang/rust#49146 will allow conditionals in constants. #![feature(const_fn, const_panic)]
#[doc(hidden)]
pub use core as core_;
#[macro_export]
macro_rules! static_assert {
($cond:expr) => {
$crate::static_assert!($cond, concat!("assertion failed: ", stringify!($cond)));
};
($cond:expr, $($t:tt)+) => {
#[forbid(const_err)]
const _: () = {
if !$cond {
$crate::core_::panic!($($t)+)
}
};
};
}
//static_assert!(1 + 1 == 3); // not actually possible yet The error messages are noisy but more descriptive than an integer overflow error:
|
Evaluation in a const context works for |
I think asserts are a pretty common thing, especially in unsafe rust (checking sizes/alignments etc.)
Now with anonymous consts we can already do things like:
I propose to add macros like this to the core library, with the whole
assert
/assert_eq
/assert_ne
facade.I think these would be really useful
The text was updated successfully, but these errors were encountered: