Skip to content
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

Consider using const_panic in the future. #43

Open
konsumlamm opened this issue Aug 19, 2021 · 3 comments
Open

Consider using const_panic in the future. #43

konsumlamm opened this issue Aug 19, 2021 · 3 comments

Comments

@konsumlamm
Copy link

Tracking issue for const_panic: rust-lang/rust#51999.

Once this gets stabilized, it would be allowed to panic in a const context, so macros like const_assert could be implemented like this:

macro_rules! const_assert {
    ($x:expr $(,)?) => {
        const _: () = if $x { () } else { panic!("static assertion failed") };
    };
}
@andylizi
Copy link

andylizi commented Oct 5, 2021

It's stabilized today.

@rodrimati1992
Copy link

Not only is it stable in the nightly channel, you can define a const_assert macro like this:

macro_rules! const_assert {
    ($x:expr $(,)?) => {
        const _: () = assert!($x);
    };
}

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=e32154ec03b111a11e1bef66caa88cf0

const_assert!(2+2==5);
error[E0080]: evaluation of constant value failed
 --> src/lib.rs:3:23
  |
3 |         const _: () = assert!($x);
  |                       ^^^^^^^^^^^ the evaluated program panicked at 'assertion failed: 2 + 2 == 5', src/lib.rs:7:1
...
7 | const_assert!(2+2==5);
  | ---------------------- in this macro invocation
  |
  = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info)

@ian-h-chamberlain
Copy link

FWIW, const_panic just landed in stable version 1.57.0, released today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants