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

deserialize: flexible defaults for missing struct fields #90

Closed
anguslees opened this issue Jun 15, 2015 · 2 comments
Closed

deserialize: flexible defaults for missing struct fields #90

anguslees opened this issue Jun 15, 2015 · 2 comments
Milestone

Comments

@anguslees
Copy link

Currently I have to define a newtype (eg: "BoolDefaultTrue") every time I want an optional struct field to have a non-Default::default() default, which is clumsy. Ideally I could just say something like:

struct Foo {
    #[serde(default=true)]
    enabled: bool,
}

... and this would fill in the value true if it was missing from the serialised string. Super-awesome would be if serde also generated a Default trait implementation for Foo that respected the same values, but I could understand that being considered out of scope.

@oli-obk
Copy link
Member

oli-obk commented Aug 13, 2015

If you create a manual Default impl for Foo, serde still uses the Default impl of the fields` type.

Example: this impl doesn't cause the #[serde(default)] to set the field to true.

impl Default for Foo {
    fn default() -> Foo {
        Foo {
            enabled: true,
        }
    }
}

@erickt: is using the surrounding type's Default impl (if present) too much magic? Alternatively requiring that the type impls Default if any field is annotated would be a breaking change and maybe not what one expects when annotating a field.

relevant code location: https://github.com/serde-rs/serde/blob/master/serde_codegen/src/de.rs#L994

@erickt
Copy link
Member

erickt commented Feb 21, 2016

This was implemented in #238!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

4 participants