How do I implement From<T> for Option<U> in Rust?

Viewed 68

Assuming I have an enum as:

enum Foo {
    A,
    B,
}

...where I want to implement something like this:

impl From<char> for Option<Foo> {
    fn from(chr: char) -> Self {
        match chr {
            'A' => Some(Foo::A),
            'B' => Some(Foo::B),
            _ => None,
        }
    }
}

This is currently illegal since Option is out of my own crate, it is owned by std. The compiler error is:

only traits defined in the current crate can be implemented for types defined outside of the crate
define and implement a trait or new type instead rustc(E0117)

As in the case I have shown above, in some cases, I'd like to have None instead of Some. Is there a way to implement a From that I am able to get Option<U> instead of U itself?


Environment

  • Rust 1.62.1
1 Answers

I think what you actually want in this scenario is to implement the TryFrom trait instead.

For example (ideally you'd make a proper Error type rather than a str):

impl TryFrom<char> for Foo {
    type Error = &'static str;

    fn try_from(chr: char) -> Result<Foo, Self::Error> {
        match chr {
            'A' => Ok(Foo::A),
            'B' => Ok(Foo::B),
            _ => Err("can't convert character to Foo"),
        }
    }
}
Related