Open BertalanD opened 4 years ago
I seem to be running into the same issue with #[serde(default, flatten)]
where my field type impls Default
.
Any workarounds for this?
Same thing, flatten
doesn't work with default
, nor with manual default trait impl nor with derive(default)
.
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct User {
#[serde(flatten, default)]
contact: Contact,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
struct Contact {
email: String,
phone: String,
}
fn main() {
let json = r#"{
"email": "john@example.com"
}"#;
let user: User = serde_json::from_str(json).unwrap();
let expected_user = User { contact: Contact { email: "john@example.com".to_string(), phone: "".to_string() } };
assert_eq!(user, expected_user);
}
panics with:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("missing field `phone`", line: 3, column: 5)', src/main.rs:20:49
This is duplicate of #1626
I have a struct A that – along with other fields – contains a flattened B struct and a collection of B structs. I would like B's missing fields to take up a different default value if they are in the flattened field.
The problem
No matter what
default
attribute I set on theflatten
-ed field, it will fall back to its type'sdefault
implementation.For flattened structs, it would mean more sense that
default
applies to each field separately, as it's a way more common use case than wanting to fall back to the struct's Default implementation unless all of its fields are missing. But I am not even sure if that's how it's currently behaving.Minimal example
These are my data structures:
And I want to deserialize the following TOML file:
Expected results when deserialized into a
value: A
:Here is the same thing in the Rust Playground (currently panics.)