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

Untagged and externally tagged enum at the same time #1646

Closed
WaffleLapkin opened this issue Oct 13, 2019 · 2 comments
Closed

Untagged and externally tagged enum at the same time #1646

WaffleLapkin opened this issue Oct 13, 2019 · 2 comments

Comments

@WaffleLapkin
Copy link

WaffleLapkin commented Oct 13, 2019

I'm not sure it's even possible, but it would be nice to have "externally tagged" variants and "untagged" variants at the same time.

Example:

#[derive(Debug, Deserialize, Serialize)]
enum Test {
    #[serde(rename = "tagged")]
    Tagged(i32),

    #[serde(untagged)]
    Untagged { field1: i32, field2: i32 }
}

#[test]
fn test() {
    let json = serde_json::to_string(&Test::Tagged(0)).unwrap();
    assert_eq!(json, r#"{"tagged":0}"#);

    let json = serde_json::to_string(&Test::Untagged { field1: 0, field2: 6 }).unwrap();
    assert_eq!(json, r#"{"field1":0,"field2":6}"#);
}

For now I'm just using

#[serde(untagged)]
enum Test {
    Tagged { tagged: i32 },
    Untagged { field1: i32, field2: i32 }
}

But there are duplication (like Tagged and tagged) in half enum variants and it isn't user-friendly (and in real life enum is much bigger and writing (de)serialization by hand can be painful)

@dtolnay
Copy link
Member

dtolnay commented Jul 9, 2023

I think I would prefer not to build this into serde_derive — but there is room for someone to create a more fully featured derive macro that can accommodate such a representation.

@dtolnay dtolnay closed this as completed Jul 9, 2023
@Mingun
Copy link
Contributor

Mingun commented Jul 10, 2023

This actually was implemented in #2403

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

3 participants