Error handling in From trait implementation

Hello,

I am trying to figure out what's the best way to propagate an error up from within the From trait implementation. My initial implementation just uses panic just to get things working, but I would like my program to better handle the error instead of exiting.

Here's the piece of code I have currently.

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Die {
    D2 = 2,
    D4 = 4,
    D6 = 6,
    D8 = 8,
    D10 = 10,
    D12 = 12,
    D20 = 20,
    D100 = 100
}

impl From<u32> for Die {
    fn from(sides: u32) -> Die {
        return match sides {
            2 => Die::D2,
            4 => Die::D4,
            6 => Die::D6,
            8 => Die::D8,
            10 => Die::D10,
            12 => Die::D12,
            20 => Die::D20,
            100 => Die::D100,
            _ => panic!("Unable to match the die type"),
        }
    }
}

There is an unstable TryFrom trait for that.

1 Like

Thanks! Looks like this is in nightly build only. I ended up implementing try_from as a function instead of from the trait.