Skip to content
This repository has been archived by the owner on Mar 25, 2024. It is now read-only.

deny_unknown_fields on empty struct #331

Closed
ibigbug opened this issue Sep 20, 2022 · 4 comments
Closed

deny_unknown_fields on empty struct #331

ibigbug opened this issue Sep 20, 2022 · 4 comments

Comments

@ibigbug
Copy link

ibigbug commented Sep 20, 2022

deny_unknown_fields on empty struct seems broken:

use serde::Deserialize;

#[derive(Deserialize, Debug)]
struct Request {
    pub a: bool,
    
}

#[derive(Deserialize, Debug)]
struct Request2;



fn main() {
    let y = r#"
    m:
    a: true
    "#;

    let requests: Request = serde_yaml::from_str(y).unwrap();
    println!("{:?}", requests);
    
      let yy = r#"
    m:
    "#;
    
    let requests2: Request2 = serde_yaml::from_str(yy).unwrap();
    println!("{:?}", requests2);
    
}

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

possibly similar to #304

@dtolnay
Copy link
Owner

dtolnay commented Sep 20, 2022

It doesn't look like you are using deny_unknown_fields in the code you pasted. Can you clarify the issue?

@ibigbug
Copy link
Author

ibigbug commented Sep 20, 2022

@dtolnay the deny_unknown_fields is by default false, and can only be turned on by setting the attribute, so it should allow unknown fields, for example in Request the field m is ignored by default.

but for Request2 is throwing error, instead of ignoring the field m.

@dtolnay
Copy link
Owner

dtolnay commented Sep 21, 2022

struct Request2; is not an empty struct, it is a unit struct. The field m isn't the issue, it's that the YAML contains a map and unit structs are not represented as maps. This is consistent with how struct Request(); (a tuple struct) would also not be valid to deserialize from a map.

An empty struct (braced struct with no fields) would be written struct Request2 {} and will deserialize from a map, ignore unknown field unless annotated serde(deny_unknown_fields).

The behavior of serde_yaml here matches the behavior of serde_json, neither {} nor {"m":null} is valid to deserialize as a unit struct in JSON either.

@ibigbug
Copy link
Author

ibigbug commented Sep 21, 2022

I see. good to know.

putting struct Request2 {} is working as expected. thank you!

@dtolnay dtolnay closed this as completed Oct 9, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants