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

Add #[derive(serde::Default)] that is aware of serde default annotations #2622

Closed
BrynCooke opened this issue Oct 6, 2023 · 3 comments
Closed

Comments

@BrynCooke
Copy link

When using serde defaulting users currently have to manually create Default implementations that match the serde annotations.

For example:

    #[test]
    fn test() {
        #[derive(Deserialize)]
        struct Container {
            a: A,
        }
        #[derive(Deserialize)]
        struct A {
            #[serde(default)]
            b: B,
        }

        #[derive(Deserialize, Default)]
        struct B {
            #[serde(default = "true_fn")]
            c: bool,
        }

        fn true_fn() -> bool {
            true
        }

        let container1 = serde_yaml::from_str::<Container>("a: {}").unwrap();
        let container2 = serde_yaml::from_str::<Container>("a: {b: {}}").unwrap();
        println!("{}", container1.a.b.c);
        println!("{}", container2.a.b.c);
    }

The output is:

true
false

This is because the implementation of Default disagrees with the serde defaults.

The current workaround for this is to manually create the default implementation of B such that it agrees exactly with serde. On large and complex structs this is almost guaranteed to lead to errors.

It'd be great if serde provided derive support for Default that is aware of the serde default annotations.

@dtolnay
Copy link
Member

dtolnay commented Oct 6, 2023

I would prefer not to build this into this crate. But this derive can be implemented in a separate crate.

@BrynCooke
Copy link
Author

Looks like such a crate already exists: https://docs.rs/serde_default/0.1.0/serde_default/

@BrynCooke
Copy link
Author

The crate listed above didn't work for me, so I created a new one: https://crates.io/crates/serde_derive_default

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