Skip to content

Better ergonomics for deserializing an enum that can turn into multiple structs #3

@GeeWee

Description

@GeeWee

I'm looking to deserialize an untagged enum into one of multiple structs.

Example of the enum I would like to use serde-untagged to serialize:

pub enum MyEnum {
    Variant1(Foo),
    Variant2(Bar),
}

pub struct Foo {
    x: String,
}

pub struct Bar {
    y: String,
}

Now I'm able to deserialize this into one of the structs easily following the documentation:

impl<'de> Deserialize<'de> for MyEnum {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        UntaggedEnumVisitor::new()
            .map(|map| {
                let deserialized_map = map.deserialize().map(MyEnum::Variant1);

                deserialized_map
            })
            .deserialize(deserializer)
    }
}

However I seem to be unable to attempt to deserialize it to multiple types of structs and get the best one. I assume this might have something to do with the fact that UntaggedEnumVisitor doesn't buffer the content, while it seems that serde does that internally via _serde::__private::de::Content.

Things I have tried.

  • Calling .map multiple times on the UntaggedEnumVisitor
  • Attempting to call map.deserialize() multiple times.
  • Attempting to clone the map closure parameter

I'm not sure if I'm missing something, if this is a docs improvement, or we need some sort of handle to persist the values of a map to allow for multiple deserialization attempts.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions