Add a way to use default field value as serde default
Author: DarkFenXCreated Jul 20, 2026Updated Jul 20, 2026
#![feature(default_field_values)]
#[derive(serde::Deserialize)]
struct S1 {
tag: i8,
data: Vec<i8> = Vec::new(),
}
#[derive(serde::Deserialize)]
struct S2 {
#[serde(default)]
field1: S1 = S1 { tag: 2, .. },
}This code fails with:
error[E0277]: the trait bound `S1: Default` is not satisfied
--> core_lib/src/lib.rs:11:5
|
11 | / #[serde(default)]
12 | | field1: S1 = S1 { tag: 2, .. },
| |__________________________________^ the trait `Default` is not implemented for `S1`
|
help: consider annotating `S1` with `#[derive(Default)]`
|
4 + #[derive(Default)]
5 | struct S1 {
|Would be nice to have a way to make serde use S1 { tag: 2, .. } as default value for S2.field1, when that field is not set during deserialization. Personally I'd say this could become the usual behavior of #[serde(default)] (do not require field type to implement Default, take default value from the one specified in struct). This way priority of sources for default would be:
- Explicitly set source in macro
- Field default value
- Default implementation of type stored in the field
If it's not possible, having alternate way of doing it (e.g. #[serde(field_default)]) works as well.
Source: serde-rs/serde