Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
GeeWee opened this issue Sep 6, 2023 · 1 comment

Comments

@GeeWee
Copy link

GeeWee commented Sep 6, 2023

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.

@dtolnay
Copy link
Owner

dtolnay commented Dec 25, 2023

This isn't something I would want to address in this crate. But I would welcome someone building a more fully featured library for untagged enum deserialization logic, based on this one, where you could express things like "if it has an 'x' field, do this, else if it has a 'y' field, do this."

@dtolnay dtolnay closed this as completed Dec 25, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants