1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
[](https://crates.io/crates/serde_derive_default)
# Usage
```toml
[dependencies]
serde_derive_default = "0.1"
```
```rust
#[derive(Deserialize, serde_derive_default::Default)]
struct MyStruct {
}
```
# Problem
When using serde defaulting users currently have to manually create a Default implementations that matches the serde field level annotations.
If you use the regular `#[derive(Default)]`, it you will get unexpected results.
For example:
```rust
#[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
}
fn main() {
let container1 = serde_yaml::from_str::<Container>("a: {}").unwrap();
let container2 = serde_yaml::from_str::<Container>("a: {b: {}}").unwrap();
if container1.a.b.c == container2.a.b.c {
println!("serde and Default match!");
} else {
println!("serde and Default do not match, this is a bug!");
}
}
```
The output is:
```
serde and Default do not match, this is a bug!
```
This is because the implementation of Default disagrees with the serde defaults.
If instead `serde_serive_default::Default` is used it will use the same annotations used by serde to create the default implementation:
```rust
#[derive(Deserialize, serde_serive_default::Default)]
struct B {
#[serde(default = "true_fn")]
c: bool,
}
```
The output is:
```
serde and Default match!
```
Note that tha above problem only manifests when using field level annotations. If you are using container level `#[serde(default)]` then the regular `#[derive(Default)]` or a manual implementation of `Default` will work as expected.
|