#serde #derive #derive-deserialize #serialization

serde_piecewise_default_derive

通过实现Default,使用serde的Option处理方式,让您可以轻松地一次性为所有字段指定默认值。

2个不稳定版本

0.2.0 2019年6月12日
0.1.0 2019年6月12日

#63#derive-deserialize

Download history 322/week @ 2024-03-31 152/week @ 2024-04-07 549/week @ 2024-04-14 220/week @ 2024-04-21 69/week @ 2024-04-28 92/week @ 2024-05-05 52/week @ 2024-05-12 20/week @ 2024-05-19 115/week @ 2024-05-26 61/week @ 2024-06-02 93/week @ 2024-06-09 58/week @ 2024-06-16 82/week @ 2024-06-23 55/week @ 2024-06-30 133/week @ 2024-07-07 72/week @ 2024-07-14

344 每月下载次数
用于 serde_piecewise_default

MIT 协议

9KB
109

serde-piecewise-default

Travis Build Status Crates.io docs.rs

使用serde的Option<T>处理方式,通过实现Default,让您可以轻松地一次性为所有字段指定默认值。

示例

use serde::Deserialize;
use serde_piecewise_default::DeserializePiecewiseDefault;

#[derive(DeserializePiecewiseDefault, PartialEq, Eq, Debug)]
struct Example {
    value: u8,
    enabled: bool,
}

impl Default for Example {
    fn default() -> Self {
        Example {
            value: 20,
            enabled: true,
        }
    }
}

let data: Example = serde_json::from_str(r#"{"value": 8}"#).unwrap();
assert_eq!(data, Example { value: 8, enabled: true });
let data: Example = serde_json::from_str(r#"{"enabled": false}"#).unwrap();
assert_eq!(data, Example { value: 20, enabled: false });
let data: Example = serde_json::from_str("{}").unwrap();
assert_eq!(data, Example { value: 20, enabled: true });

实现细节

#[derive(DeserializePiecewiseDefault)]
struct Example {
    item1: i8,
    item2: String,
}

将展开为

struct Example {
    item1: i8,
    item2: String,
}

#[derive(Deserialize)]
struct OptionExample {
    item1: Option<i8>,
    item2: Option<String>,
}

impl<'de> Deserialize<'de> for Example {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
        <OptionExample as Deserialize>::deserialize(deserializer)
            .map(|raw_result| {
                let OptionExample { item1, item2 } = raw_result;
                let default = <Example as Default>::default();
                let item1 = item1.unwrap_or(default.item1);
                let item2 = item2.unwrap_or(default.item2);
                Example { item1, item2 }
            })
    }
}

lib.rs:

有关更多信息,请参阅父crate文档

依赖项

~0.5–1MB
~25K SLoC