unreachable!() #
The unreachable!()
macro in Rust is used to indicate a section of the code that should never be reached under normal circumstances. Itโs useful in places where the compiler canโt determine that some code is unreachable.
If the execution of the program ever does reach a point marked with unreachable!()
, the program will immediately panic and terminate. This is because unreachable!()
is essentially a shorthand for panic!()
with a specific message indicating that unreachable code was reached.
Hereโs an example:
fn foo(x: Option<i32>) {
match x {
Some(n) if n >= 0 => println!("Some(Non-negative)"),
Some(n) if n < 0 => println!("Some(Negative)"),
Some(_) => unreachable!(), // This line should never be reached
None => println!("None"),
}
}
In this example, if foo
is called with an Option<i32>
that matches Some(_)
but doesnโt match either of the conditions n >= 0
or n < 0
, the unreachable!()
macro will cause the program to panic.
Itโs important to note that if the unreachable!()
macro is used incorrectly and the code does reach that point, it could lead to a program crash. Therefore, it should be used with caution and only when youโre certain that the code section cannot be reached.