`From<!>` & `From<Infallible>` usage

Browsing through docs I saw some weird trait implementations, for example:

impl From<Infallible> for TryFromIntError {
    fn from(x: Infallible) -> TryFromIntError {
        match x {}
    }
}

I know it could be place somewhere where we need TryFromIntError, but at the same time it will never get invoked. It looks like it's there because of some generics requirements (?), but I can't think of proper, logical usage of it. I don't want to use it, just want to know the philosophy behind this.

I suspect this is magic required to establish connection between From and TryFrom traits.

The best history I can find is this design comment:

impl<T> From<Infallible> for T so that it's compatible in ? with any error type

and a small followup why it had to be reduced to for TryFromIntError.

It's so you can return a single error type across implementations that return (or "return") either TryFromIntError or Infallible.

fn example<T: TryFrom<u32>>() -> Result<T, TryFromIntError>
where
    TryFromIntError: From<T::Error>,
{
    T::try_from(u32::MIN)?;
    Ok(T::try_from(u32::MAX)?)
}

fn main() {
    dbg!(example::<u32>());
    dbg!(example::<NonZeroU32>());
    dbg!(example::<u16>());
}
4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.