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

Content in adjacently tagged enums does/can not use default when missing #2088

Closed
Emilgardis opened this issue Sep 4, 2021 · 1 comment
Closed

Comments

@Emilgardis
Copy link

Emilgardis commented Sep 4, 2021

I want to do as shown in below example, but it doesn't seem to work. I feel like there is something I'm missing or serde is missing.

I'd solve this by making two enums, one that is the real enum, and one that is only used (and seen) in a custom deserialize. But I don't like that pattern, so I want to know if there's something that can be improved here.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=2bf7a3b1c76f9fe9d7741dce671011cf

// [dependencies]
// serde = {version = "1", features = ["derive"]}
// serde_json = "1"

use serde;
use serde_json;

#[derive(serde::Deserialize)]
pub struct Foo {
    pub bar: i64,
}

#[derive(serde::Deserialize, Default)]
pub struct NoContent {}

#[derive(serde::Deserialize)]
#[serde(tag = "tag", content = "content")]
#[serde(rename_all = "snake_case")]
pub enum Data {
    WithContent(Foo),
    WithOptContent(Option<NoContent>),
    // There is no way to make this work.
    WithoutContent(#[serde(default)] NoContent),
}

#[test]
fn deserialize() {
    let things = vec![
        r#"{"tag":"with_content", "content": { "bar": 10}}"#, // This works fine
        r#"{"tag":"with_opt_content"}"#, // This works because the content is wrapped with an Option
        r#"{"tag":"without_content" }"#, // This fails
    ];
    for i in things {
        serde_json::from_str::<Data>(i).unwrap_or_else(|_| panic!("failed on {:?}", i));
    }
}
@dtolnay
Copy link
Member

dtolnay commented Jan 23, 2022

Please take this question to one of the resources listed in https://github.com/serde-rs/serde/tree/v1.0.135#getting-help. Sorry that no one was able to provide guidance here.

@dtolnay dtolnay closed this as completed Jan 23, 2022
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

2 participants