Rust Empty Type

(Jin Qing’s Column, Sep., 2024)

Crate void defines an empty type enum Void {}.

Empty type is an enum with no variants. Empty type can not be instantiated.
See: https://doc.rust-lang.org/nomicon/exotic-sizes.html

Void is used in statically impossible cases (type-level unreachability).
For instance, a return type of Result<T, Void> indicates that it always returns Ok.

Trait void::ResultVoidErrExt can be used to unwrap the result, statically indicating the unreachability.

impl<T> ResultVoidExt<T> for Result<T, Void> {
    /// Get the value out of an always-ok Result.
    ///
    /// Never panics, since it is statically known to be Ok.
    #[inline]
    fn void_unwrap(self) -> T {
        match self {
            Ok(val) => val,
            Err(e) => unreachable(e)
        }
    }
}

rust-libp2p\swarm\src\dummy.rs uses Void to indicate that FromBehaviour event is impossible.

impl crate::handler::ConnectionHandler for ConnectionHandler {
    type FromBehaviour = Void;
    ...

    fn on_behaviour_event(&mut self, event: Self::FromBehaviour) {
        void::unreachable(event)
    }
...
}