'How to apply a function to the active enum member like C++'s std::visit?

I have a serialization library in C++ which serializes types into buffers for transmitting over network and to disk and I want to port it to Rust. The library supports serializing std::variant types that contain serializable types using the index and std::visit which can be used with a template lambda to serialize the active member in the variant:

template<Serializable ... Object>
void serialize_variant(const std::variant<Object...>& var) {
    serialize_number(var.index());
    std::visit([](const auto& item) { serialize_object(item); }, var);
}

Rust has match which is useful when I know the enum's type but I can't match on an arbitrary enum. I also can't get the index of the member of an enum to serialize it before the item.

I have something like this incorrect code:

trait Serilizable {
    fn write_to_buffer(&self, buff: &[u8]) {}
}

impl Serilizable for i32 {
    /* implement serilization */
}
impl Serilizable for f64 {
    /* implement serilization */
}
impl Serilizable for String {
    /* implement serilization */
}

enum ToSerialize {
    I32(i32),
    F64(f64),
    Str(String),
}

fn serialize_object(obj: &Serilizable, buff: &[u8]) {
    obj.write_to_buffer(buff);
}

fn serialize_manually(var: &ToSerialize, buff: &[u8]) {
    match ToSerialize {
        I32(i) => {
            serialize_object(&0, buff);
            serialize_object(i, buff);
        }
        F64(f) => {
            serialize_object(&1, buff);
            serialize_object(i, buff);
        }
        Str(s) => {
            serialize_object(&2, buff);
            serialize_object(s, buff);
        }
    }
}

I want to replace serialize_manually with a generic function that accepts any enum of Serializable types and does something similar.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source