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

(Nested) enums provided with the #[serde(tag = "type")]-containing anonymus enum types fail during serialisation. #2430

Closed
gomolsoft opened this issue Apr 23, 2023 · 1 comment

Comments

@gomolsoft
Copy link

If a toplevel enum contains a nested enum both are provided with the "#[serde(tag = "type")]" and the nested enum contains, among other things, an anonymous string, an error occurs during serialisation:

use serde::{Deserialize, Serialize};

#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum EnumNested {
    SimpleType, 
    WithString(String),
}

#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum EnumTopLevel {
    NestedEnumType {
      name: String,
      nested: Option<EnumNested>,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_struct_output_v1() {
        let enum_type = EnumTopLevel::NestedEnumType {
            name: "test..123".to_string(),
            nested: Some(EnumNested::WithString("some... ".to_string())),
         };
         
        let serialized = serde_json::to_string(&enum_type).unwrap(); 
    }
}

The following error occures:

Error("cannot serialize tagged newtype variant EnumNested::WithString containing a string"
-> let serialized = serde_json::to_string_pretty(&enum_type).unwrap(); 

running 1 test
test tests::test_struct_output_v1 ... FAILED

failures:

---- tests::test_struct_output_v1 stdout ----
thread 'tests::test_struct_output_v1' panicked at 'called Result::unwrap() on an Err value: Error("cannot serialize tagged newtype variant EnumNested::WithString containing a string", line: 0, column: 0)', src/lib.rs:34:71
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace

failures:
tests::test_struct_output_v1

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

@dtolnay
Copy link
Member

dtolnay commented Apr 23, 2023

This is working correctly as far as I can tell. https://serde.rs/enum-representations.html#internally-tagged documents that tag = "type" is for struct variants, newtype variants containing structs or maps, and unit variants — which is not what WithString is.

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