问题描述
Serde 支持应用与 #[derive(Serialize)]
一起使用的自定义属性:
Serde supports applying custom attributes that are used with #[derive(Serialize)]
:
#[derive(Serialize)]
struct Resource {
// Always serialized.
name: String,
// Never serialized.
#[serde(skip_serializing)]
hash: String,
// Use a method to decide whether the field should be skipped.
#[serde(skip_serializing_if = "Map::is_empty")]
metadata: Map<String, String>,
}
我了解如何实现程序宏(本例中为Serialize
),但我应该如何实现#[serde(skip_serializing)]
?我无法在任何地方找到这些信息.docs 甚至没有提到这一点.我曾尝试查看 serde-derive
源代码,但它对我来说非常复杂.
I understand how to implement a procedural macro (Serialize
in this example) but what should I do to implement #[serde(skip_serializing)]
? I was unable to find this information anywhere. The docs don't even mention this. I have tried to look at the serde-derive
source code but it is very complicated for me.
推荐答案
您在字段上实现属性作为结构派生宏的一部分(您只能为结构和枚举实现派生宏).
You implement attributes on fields as part of the derive macro for the struct (you can only implement derive macros for structs and enums).
Serde 通过检查 syn
提供的结构中的每个字段的属性并相应地更改代码生成来做到这一点.
Serde does this by checking every field for an attribute within the structures provided by syn
and changing the code generation accordingly.
您可以在这里找到相关代码:https://github.com/serde-rs/serde/blob/master/serde_derive/src/internals/attr.rs
You can find the relevant code here: https://github.com/serde-rs/serde/blob/master/serde_derive/src/internals/attr.rs
这篇关于如何在程序宏中处理枚举/结构/字段属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!