#Macro to destructure enum

2 messages · Page 1 of 1 (latest)

still stag
#

I want to make my enum impl From and TryInto for it's inner types.

macro_rules! impl_nbt_convert {
    ($c:expr, $t:ty) => {
        impl From<$t> for NBT {
            fn from(value: $t) -> Self {
                $c(value)
            }
        }

        impl TryInto<$t> for NBT {
            type Error = Self;

            fn try_into(self) -> Result<$t, Self> {
                match self {
                    $c(value) => Ok(value),
                    _ => Err(self)
                }
            }
        }
    };
}

impl_nbt_convert!(NBT::Byte, i8);
impl_nbt_convert!(NBT::Short, i16);
impl_nbt_convert!(NBT::Int, i32);
impl_nbt_convert!(NBT::Long, i64);
impl_nbt_convert!(NBT::Float, f32);
impl_nbt_convert!(NBT::Double, f64);
impl_nbt_convert!(NBT::List, List);
impl_nbt_convert!(NBT::Compound, HashMap<String, NBT>);

I'm getting an error in the match statement because the compiler doesn't like that I'm using an expression in the pattern. I tried passing in the enum variants as pat but if I do something like NBT::Byte as a pattern I can't append the string (value) to get the inner value, and if I do NBT::Byte(value) then it doesn't recognise value as being in scope.

dark sonnet
#

Seems fine if you use $c:path