#reflection #macro-derive #derive #run-time #struct #field-value #schema

过程宏 avocado-schema-derive

用于支持结构体值运行时反射的 derive 宏

4 个版本 (2 个重大更新)

0.8.0 2023年11月3日
0.7.0 2023年11月3日
0.6.3 2023年11月2日
0.6.2 2023年11月2日

#14#field-value

MIT 许可证

98KB
2.5K SLoC

Avocado Schema Derive

Avocado Schema 定义了以下枚举 FieldValue 用于运行时反射结构体的结构和值

Crates.io MIT licensed

#[derive(Debug, Clone, PartialEq)]
pub enum FieldValue {
    String(String),
    Integer(i64),
    UInteger(u64),
    Float(f64),
    Boolean(bool),
    Object(BTreeMap<String, FieldValue>),
    Array(Vec<FieldValue>),
    Email(EmailAddress),
    DateTime(DateTime<Utc>),
    Date(NaiveDate),
    Time(NaiveTime),
    Null,
}

此宏 Reflect 用于为结构体 derive FieldValue 枚举

#[derive(Reflect)]
struct Client {
    #[reflect("firstName")]
    first_name: String,
    #[reflect("lastName")]
    last_name: String,
    age: u64,
    #[reflect(ignore)]
    email: String
}

#[test]
fn main() {
    let client = Client {
        first_name: "Robert".to_string(),
        last_name: "Li".to_string(),
        age: 30,
        email: "[email protected]".to_string(),
    };
    assert_eq!(
        client.field_value(),
        FieldValue::Object(BTreeMap::from([
            (
                "firstName".to_string(),
                FieldValue::String("Robert".to_string())
            ),
            ("lastName".to_string(), FieldValue::String("Li".to_string())),
            ("age".to_string(), FieldValue::UInteger(30))
        ]))
    )
}

依赖项

~7–10MB
~172K SLoC