我有一个使用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)]字段属性不接受struct类型的默认值,而是每个字段的类型。(即不使用impl Default for Example。使用impl Default for i32 )。
End编辑.
我可以像这样使用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是必需的,而a、b和c则有默认值。
但是,除了一个字段之外,复制粘贴#[serde(default)]似乎不是一个好的解决方案(我的结构有10个字段)。有更好的办法吗?
发布于 2021-01-30 22:58:34
响应您的编辑,您可以利用#[serde(default = "path")]为每个字段设置默认值。路径指向返回该字段默认值的函数。
参考资料: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
}https://stackoverflow.com/questions/65844153
复制相似问题