explicit

Trait UnreachableExt

Source
pub trait UnreachableExt: Sealed {
    // Required method
    fn uninstantiable_unreachable<T>(&self) -> T;
}
Expand description

A trait providing unreachability assertion enforced by the type system.

§Example

use core::convert::Infallible as Never;

/// Provides guaranteed winning lottery numbers.
trait LotteryOracle {
  fn get_winning_number(&self) -> u32;
}

// Might return a thing that gives winning lottery numbers.
fn try_get_lottery_oracle() -> Option<impl LotteryOracle> {
  // This function always returns `None` but we still need a type that
  // the option _could_ hold.

  /// Uninstantiable type that implements [`LotteryOracle`].
  struct UninstantiableOracle(Never);

  /// Enable use with [`UnreachableExt`].
  impl AsRef<Never> for UninstantiableOracle {
    fn as_ref(&self) -> Never {
      &self.0
    }
  }

  /// Trivial implementation that can't actually be used.
  impl LotteryOracle for UninstantiableOracle {
    fn get_winning_number(&self) -> u32 {
      self.uninstantiable_unreachable()
    }
  }

  Option::<UninstantiableOracle>::None
}

§Implementing

This trait is blanket-implemented for any type that can be used to construct an instance of Never. To use it, simply implement AsRef<Never>.

Required Methods§

Source

fn uninstantiable_unreachable<T>(&self) -> T

A method that can’t be called.

This method returns an instance of any caller-specified type, which makes it impossible to implement unless the method receiver is itself uninstantiable. This method is similar to the unreachable! macro, but should be preferred over the macro since it uses the type system to enforce unreachability where unreachable! indicates a logical assertion checked at runtime.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§