Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

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

I have a struct that uses the #[serde(default)] container attribute.

But there is one field that should be required (if this field doesn't exist in the incoming data, the deserializer should error out instead of falling back to default value).

#[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.
}

Edit:

The information below isn't correct. The #[serde(default)] field attribute does not take the default value of the struct type, but rather of each field's type. (i.e. impl Default for Example isn't used. impl Default for i32 is used).

End Edit.

I could use the #[serde(default)] field attribute like this:

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

So important would be required, while a, b, and c would have default values.

But copy-pasting #[serde(default)] for all but one field doesn't seem like a good solution (my struct has ~10 fields). Is there a better way?

question from:https://stackoverflow.com/questions/65844153/serde-use-container-serdedefault-but-with-some-required-fields

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Responding to your edit you can utilize #[serde(default = "path")] to set the default values for each field. The path is to a function that returns the default value for that field.

Reference: https://serde.rs/field-attrs.html

Example:

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...