Serde:使用容器#[serde(default)],但有一些必填字段

Serde: use container #[serde(default)], but with some required fields

我有一个使用 the #[serde(default)] container attribute.

的结构

但是有一个字段应该是必需的(如果传入数据中不存在该字段,反序列化器应该出错而不是回退到默认值)。

#[serde(default)]
#[derive(Serialize, Deserialize)]
struct Example {
  important: i32, // <-- I want this field to be required.
  a: i32, //  <-- If this field isn't in the incoming data, fallback to the default value.
  b: i32, //  <-- If this field isn't in the incoming data, fallback to the default value.
  c: i32, //  <-- If this field isn't in the incoming data, fallback to the default value.
}

编辑:

以下信息不正确。 #[serde(default)] field 属性不采用结构类型的默认值,而是每个字段的类型。 (即不使用 impl Default for Example。使用 impl Default for i32)。

结束编辑。

我可以这样使用 the #[serde(default)] field attribute

#[derive(Serialize, Deserialize)]
struct Example {
  important: i32,
  #[serde(default)]
  a: i32,
  #[serde(default)]
  b: i32,
  #[serde(default)]
  c: i32,
}

因此需要 important,而 abc 将具有默认值。

但是复制粘贴 #[serde(default)] 除了一个字段之外的所有字段似乎不是一个好的解决方案(我的结构有大约 10 个字段)。 有没有更好的方法?

响应您的编辑,您可以使用 #[serde(default = "path")] 为每个字段设置默认值。该路径指向 returns 该字段的默认值的函数。

参考:https://serde.rs/field-attrs.html

示例:

const A_DEFAULT: i32 = 1;
const B_DEFAULT: i32 = 2;
const C_DEFAULT: i32 = 3;

#[derive(Serialize, Deserialize)]
struct Example {
  important: i32,
  #[serde(default = "a_default")]
  a: i32,
  #[serde(default = "b_default")]
  b: i32,
  #[serde(default = "c_default")]
  c: i32,
}

fn a_default() -> i32{
  A_DEFAULT
}
fn b_default() -> i32{
  B_DEFAULT
}
fn c_default() -> i32{
  C_DEFAULT
}