#serialization #serde #deserialize #declaration #u32 #serde-json

macro serde-inline-default

Serde default values via inline declaration

6 releases

0.2.3 Dec 2, 2024
0.2.2 Oct 14, 2024
0.2.1 Sep 24, 2024
0.2.0 Jan 26, 2024
0.1.1 Feb 11, 2023

#429 in Encoding

Download history 5180/week @ 2024-12-17 1209/week @ 2024-12-24 2499/week @ 2024-12-31 6471/week @ 2025-01-07 4909/week @ 2025-01-14 5064/week @ 2025-01-21 6791/week @ 2025-01-28 7651/week @ 2025-02-04 7813/week @ 2025-02-11 8492/week @ 2025-02-18 8297/week @ 2025-02-25 10990/week @ 2025-03-04 7475/week @ 2025-03-11 14260/week @ 2025-03-18 11683/week @ 2025-03-25 19400/week @ 2025-04-01

54,563 downloads per month
Used in 12 crates (10 directly)

MIT/Apache

11KB
88 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

~210–650KB
~15K SLoC