Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a match on an empty enum return?

Tags:

enums

rust

When reading Rust's convert.rs, I encountered the following code:

#[unstable(feature = "try_from", issue = "33417")]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Infallible {}

#[unstable(feature = "try_from", issue = "33417")]
impl fmt::Display for Infallible {
    fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
        match *self {
        }
    }
}

Infallible is an empty enum with no variants. What does match *self {} return?

like image 496
Cheng-Chang Wu Avatar asked Dec 01 '17 08:12

Cheng-Chang Wu


1 Answers

Since Infallible has no possible values, you can never have an instance of it. This means matching on it can never happen. Rust represents this by making matching on an empty enum yield the ! type, which is a builtin type that has no values.

This type coerces to any other type, because the statement can never be reached, because you'd need a value of type Infallible for that, which you can't have out of obvious reasons.

like image 136
oli_obk Avatar answered Oct 04 '22 20:10

oli_obk