Implement from char for option?

Hello everyone,

Sorry for the beginner question...

Is it possible to implement From trait for Option?

I tried something like this...

use std::{char, option::Option};


impl From<char> for Option<Piece> {
    fn from(c: char) -> Option<Piece> {
        match c {
            'p' => Some(Piece::Pawn(Color::Black)),
            'n' => Some(Piece::Knight(Color::Black)),
            'b' => Some(Piece::Bishop(Color::Black)),
            'r' => Some(Piece::Rook(Color::Black)),
            'q' => Some(Piece::Queen(Color::Black)),
            'k' => Some(Piece::King(Color::Black)),
            'P' => Some(Piece::Pawn(Color::White)),
            'N' => Some(Piece::Knight(Color::White)),
            'B' => Some(Piece::Bishop(Color::White)),
            'R' => Some(Piece::Rook(Color::White)),
            'Q' => Some(Piece::Queen(Color::White)),
            'K' => Some(Piece::King(Color::White)),
            _ => None,

... but it fails with this error

impl doesn't use only types from inside the current crate
note: define and implement a trait or new type insteadrustc(E0117), 1): impl doesn't use only types from inside the current crate, 6): `char` is not defined in the current crate, 21): `std::option::Option` is not defined in the current crate

Is it because of char? or Option?

I also do not understand why char and Option are not defined, even with use at the start.

Thanks for taking time

No, because of the "orphan rules": You don't own the trait From or the implementer Option. (The actual rules are more complicated, but this is common first approximation.) This is what the error is talking about when it says "is not defined in the current crate". I agree the wording is easy to misunderstand.

For this particular case, it looks like you probably want to implement TryFrom<char> for Piece instead.


Thank You for your quick response.

I will check the TryFrom trait.

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.