I'm using the num_enum crate to convert enum variants into/from a primitive (I don't know why Rust doesn't provide this out of the box).
The problem is that it returns a generic error TryFromPrimitiveError<Enum: TryFromPrimitive>
. Is it possible to convert a generic error into my own?
I'm currently using map_err
everywhere but the code becomes very messy.
Preferably I would want something like this (doesn't compile):
use num_enum::{TryFromPrimitive, TryFromPrimitiveError};
#[repr(u8)]
#[derive(Debug, PartialEq, Eq, TryFromPrimitive)]
enum Foo {
A = 1,
B = 2,
C = 3,
}
#[repr(u8)]
#[derive(Debug, PartialEq, Eq, TryFromPrimitive)]
enum Bar {
X = 4,
Y = 5,
Z = 6,
}
#[derive(Debug)]
enum MyError {
EnumError(TryFromPrimitiveError<Enum>),
}
impl From<TryFromPrimitiveError<Enum>> for MyError {
fn from(error: TryFromPrimitiveError<Enum>) -> Self {
MyError::EnumError(error)
}
}
fn main() -> Result<(), MyError> {
let b = Foo::try_from(2)?;
assert_eq!(b, Foo::B);
let wrong = Bar::try_from(8)?;
Ok(())
}