Skip to content

Add an optional string parameter to the unreachable!() macro to communicate which invariant was violated #18842

Closed
@bstrie

Description

@bstrie

In #18287 we had the submitter change a panic!() to an unreachable!() as follows:

_ => panic!("Invalid SearchStack.")
_ => unreachable!()

We felt that unreachable!() better communicated the intent of "this code should never panic assuming that the implementation is correct" (as opposed to panic!(), which communicates "this code should never panic assuming that the user passes in the correct inputs" (cf. indexing, division) and is generally to be avoided in the stdlib).

However, I think it's a shame that by expressing the intent more clearly in the code we're simultaneously losing information regarding which invariant was violated in order to reach the unreachable code.

Note that this isn't really a huge deal, because we can just move the "Invalid SearchStack" bit over into a comment next to unreachable!(). It's also not really a huge deal for the theoretical bug reporter who's filing an issue upon hitting this code, since unreachable!() still includes a filename and line number in its output.

However, given the precedent of optional messages set by panic!(), I don't think it would be a stretch to imagine that unreachable!() could also have an optional message. Usage for the typical case would be the same:

unreachable!();  // task '<main>' panicked at 'internal error: entered unreachable code', unreachable.rs:2

...but could optionally look like this:

unreachable!("bamboozled the frobnob");  // task '<main>' panicked at 'internal error: entered unreachable code: bamboozled the frobnob', unreachable.rs:2

Metadata

Metadata

Assignees

No one assigned

    Labels

    E-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.P-lowLow priority

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions