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

Extra fields treated as belonging to flattened unit struct rather than being ignored #2775

Open
ss2165 opened this issue Jul 8, 2024 · 0 comments

Comments

@ss2165
Copy link

ss2165 commented Jul 8, 2024

serde_json example, but have checked the same problem occurs with serde_yaml:

    #[derive(Serialize, Deserialize)]
    struct Unit;

    #[derive(Serialize, Deserialize)]
    enum UnitOrNot {
        Unit(Unit),
        NotUnit { field: String },
    }
    #[derive(Serialize, Deserialize)]
    struct Nested {
        #[serde(flatten)]
        inner: UnitOrNot,
    }

    let data = r#"
    [
        {
            "NotUnit": {
                "field": "value",
                "ignored": "bar"
            }
        },
        {
            "Unit": {
                "ignored": "foo"
            }
        }
    ]"#;

    let _: Vec<Nested> = serde_json::from_str(data).unwrap();

The first element of the array successfully deserializes and ignores the extra "ignored" field. The second fails with:

Error: Error("invalid type: map, expected unit struct Unit", line: 11, column: 13)

(i.e. the extra field is now treated as belonging to the unit struct).

The code succeeds if you change the definition of Unit to

struct Unit {}
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

1 participant