Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any performance advantages in using `unreachable!` vs `panic!`?

Tags:

rust

Is the existence of unreachable! macro purely for the sake of clarity when reading code, or does it provide any functional advantages?

like image 971
John Avatar asked May 30 '17 06:05

John


1 Answers

Yes the unreachable! macro (and unimplemented! too) are purely for clarity. They are implemented to directly forward to panic!.

#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! unreachable {
    () => ({
        panic!("internal error: entered unreachable code")
    });
    ($msg:expr) => ({
        unreachable!("{}", $msg)
    });
    ($fmt:expr, $($arg:tt)*) => ({
        panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
    });
}

#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! unimplemented {
    () => (panic!("not yet implemented"))
}

Not to be confused with the unreachable intrinsic (accessible in stable Rust via the unreachable or debug_unreachable crates), which unsafely asserts a branch is totally unreachable. This allows the branch to be completely removed when optimizing. It could lead to undefined behavior if the assertion turns out to be wrong, compared with unreachable!() which only panics.

like image 132
kennytm Avatar answered Sep 28 '22 05:09

kennytm