Expand description
definitely::unreachable!()
is a macro for marking codepaths that are known
to be statically unreachable by the compiler’s intraprocedural control flow
analysis, to ensure that they remain unreachable.
This complements the standard library’s
unsafe { core::hint::unreachable_unchecked() }
function and core::unreachable!()
macro.
safety | runtime behavior | binary size | |
---|---|---|---|
core::hint::unreachable_unchecked | unsafe | undefined behavior if reached | zero |
core::unreachable | safe | panic if reached | nonzero |
definitely::unreachable | safe | impossible to reach | zero |
§Example
This use case has some complicated control flow involving retrying an API
call with a succession of different arguments in reaction to previous
observed failures. While there is a loop
in the code, we would like to be
sure that every path through this loop body ends explicitly in a specific
intentional return
or break
or continue
or panic. It should not be
possible for this to become an implicit infinite loop during the course of
future refactorings.
let mut retry_with_a = false;
let mut retry_with_b = false;
loop {
let mut arg = "...";
if retry_with_a {
arg = alternate(arg);
}
let thing = do_thing(arg, retry_with_b.then_some(b));
match thing {
Ok(outcome) => {
return outcome;
}
Err(err) if !retry_with_a && err.kind() == ErrorKind::NotFound => {
retry_with_a = true;
continue;
}
Err(err) if !retry_with_b => {
retry_with_b = true;
continue;
}
Err(err) => {
eprintln!("{}", err);
return default_value();
}
}
definitely::unreachable!();
}