unsafe {} block is a marker to force compiler to trust whatever you says. It's up to you to not trigger any UB, otherwise the compiler would generate garbage binary like the ones you can get from C/++ compiler.
But yeah, I forgot the panic in const feature is not stabilized. Good news is it seems to be merged soon™.
error[E0401]: can't use generic parameters from outer function
--> src/main.rs:9:26
|
8 | fn Bar<T: Foo>() {
| - type parameter from outer function
9 | const_assert_ne!(T::NON_ZERO, 0);
| ^^^^^^^^^^^ use of generic parameter from outer function
You can even push stuff further and start using helper traits and const bool-dispatching to generate an error message rather nice :
error[E0277]: the trait bound `Const<0_usize>: IsNonZero` is not satisfied
--> src/lib.rs:16:40
|
16 | const NON_ZERO: NonZeroUsize = non_zero!(0);
| ^^^^^^^^^^^^ the trait `IsNonZero` is not implemented for `Const<0_usize>`
However, this is just a snapshot of what rustc currently does. None of this is guaranteed , and rustc may relax or otherwise change its UB checking any time.
macro_rules! to_nonzero {
($value:expr) => {{
const VALUE: NonZeroUsize = {
let value = $value;
match NonZeroUsize::new(value) {
Some(x) => x,
None => [/* expected non-zero value */][value],
}
};
VALUE
}};
}
error: any use of this value will cause an error
--> src/main.rs:7:22
|
3 | / const VALUE: ::core::num::NonZeroUsize = {
4 | | let value = $value;
5 | | match ::core::num::NonZeroUsize::new(value) {
6 | | ::core::option::Option::Some(x) => x,
7 | | _ => [/* expected non-zero value */][value],
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ index out of bounds: the length is 0 but the index is 0
8 | | }
9 | | };
| |__________-
...
15 | to_nonzero!(0);
| --------------- in this macro invocation
|
= note: `#[deny(const_err)]` on by default
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
= note: for more information, see issue #71800 <https://github.com/rust-lang/rust/issues/71800>
= note: this error originates in the macro `to_nonzero` (in Nightly builds, run with -Z macro-backtrace for more info)