Serialize enum without an external lib

Hello world. I save my app's data into a binary file. I would like to save values of enum type too. I can get their discriminants as number, but then, I don't find how to get a variant through its discriminant. Please help me.

Heavily simplified, this is the basic idea of how serde handles serialization of enums:

enum Data {
    A(A),
    B(B),
    C(C),
}

struct A;
struct B;
struct C;

impl Data {
    fn serialize(self) {
        match self {
            Self::A(a) => {
                serialize(0);
                serialize(a);
            }
            Self::B(b) => {
                serialize(1);
                serialize(b);
            }
            Self::C(c) => {
                serialize(2);
                serialize(c);
            }
        }
    }

    fn deserialize() -> Self {
        let discriminant = i32::deserialize();
        match discriminant {
            0 => Self::A(A::deserialize()),
            1 => Self::B(B::deserialize()),
            2 => Self::C(C::deserialize()),
            _ => panic!(),
        }
    }
}

Serde uses macros to generate all the necessary code automatically. If you don't want to use a library, you'll need to write this code or a macro yourself.

1 Like

I wanted to avoid match expressions, but I think I don't have another way :sweat_smile:

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.