#serde-default #default-value #serialization #serde-serialize #serde #inline #set

macro serde-inline-default

Serde default values via inline declaration

3 unstable releases

0.2.0 Jan 26, 2024
0.1.1 Feb 11, 2023
0.1.0 Feb 11, 2023

#504 in Encoding

Download history 547/week @ 2023-12-18 190/week @ 2023-12-25 464/week @ 2024-01-01 1133/week @ 2024-01-08 1070/week @ 2024-01-15 1678/week @ 2024-01-22 1932/week @ 2024-01-29 2179/week @ 2024-02-05 2495/week @ 2024-02-12 2100/week @ 2024-02-19 2259/week @ 2024-02-26 1576/week @ 2024-03-04 2419/week @ 2024-03-11 2536/week @ 2024-03-18 2219/week @ 2024-03-25 2068/week @ 2024-04-01

9,367 downloads per month
Used in 6 crates (5 directly)

MIT/Apache

10KB
56 lines

serde-inline-default ci crates.io docs

Tiny crate to set default values for serde fields via inline attribute declaration.

Overview

This crate is an approach to do what serde-rs/serde#368 purposes. If you want to set default values in plain serde, you have to create a function and link to it with #[serde(default = "..."). This may be good if you need to do calculations to get the default value, but often you just want a simple integer or string to be the default value and have to create a whole function to return a hard-coded value.

#[derive(Deserialize)]
struct Test {
    #[serde(default = "value_default")]
    value: u32
}

fn value_default() -> u32 { 42 }

That can get quiet messy if you have many fields with many (different) default values. This crate tries to solve this issue by providing the #[serde_inline_default] proc macro. With this macro set at the struct level (before #[derive(Deserialize)]/#[derive(Serialize)]!, otherwise it's not working correctly), you can set default values via #[serde_inline_default(...)] for your serde fields inline, without creating an extra function.

#[serde_inline_default]
#[derive(Deserialize)]
struct Test {
    #[serde_inline_default(42)]
    value: u32
}

Internally, #[serde_inline_default(...)] gets expanded to a function which returns the set value and the attribute is replaced with #[serde(default = "<function name>")]. So this macro is just some syntax sugar for you, but can get quiet handy if you want to keep your code clean or write declarative macros / macro_rules!.

License

This project is licensed under either of the following licenses, at your option:

Dependencies

~345–800KB
~19K SLoC