我试图做一个宏修改结构体的声明,现在我有这个:
macro_rules! Reflect
{
(pub struct $name:ident {$($field_name:ident : $field_type:ty,) *}) =>
{
#[derive(Debug, Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct $name
{
$(pub $field_name : $field_type,) *
}
}
Reflect!(
pub struct Node
{
name : String,
#[serde(skip_serializing_if = "<[_]>::is_empty")] // causes compilation error because macro does not expect it
children : Vec::<usize>,
rotation : na::UnitQuaternion::<f32>,
translation : na::Vector3::<f32>,
scale : na::Vector3::<f32>,
skin : usize,
mesh : usize,
}
);
在这种情况下,如果定义了,我希望serde属性声明在字段的顶部保持完整。
使用上面的代码,我得到一个编译错误,因为宏没有正确的模式来处理它,但我不知道如何做。
您可以使用:meta
片段捕获属性:
macro_rules! Reflect
{
(
pub struct $name:ident {
$(
$( #[$attrs:meta] )*
$field_name:ident : $field_type:ty,
)*
}
) =>
{
#[derive(Debug, Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct $name
{
$(
$( #[$attrs] )*
pub $field_name : $field_type,
)*
}
};
}