【发布时间】:2023-10-02 15:41:01
【问题描述】:
我正在尝试编写一个 Rust 宏,它允许我使用结构声明的字段名称和类型,但我仍然需要发出结构。
我已经让它与可选属性、结构的可见性一起使用(感谢The Little Book of Rust Macros),但无法弄清楚如何处理各个字段中pub 的可选存在。
到目前为止,我得到了:
macro_rules! with_generic {
($(#[$struct_meta:meta])*
pub struct $name:ident { $($fname:ident : $ftype:ty), *}
) => {
with_generic![(pub) $(#[$struct_meta])* struct $name {$($fname: $ftype) ,*}];
};
($(#[$struct_meta:meta])*
struct $name:ident { $($fname:ident : $ftype:ty), *}
) => {
with_generic![() $(#[$struct_meta])* struct $name {$($fname: $ftype), *}];
};
(
($($vis:tt)*)
$(#[$struct_meta:meta])*
struct $name:ident { $($fname:ident : $ftype:ty), *}
) => {
// emit the struct here
$(#[$struct_meta])*
$($vis)* struct $name {
$($fname: $ftype,)*
}
// I work with fname and ftypes here
}
}
它适用于类似的东西
with_generic! {
#[derive(PartialEq, Eq, Debug)]
pub struct Person {
first_name: String,
last_name: String
}
}
或
with_generic! {
#[derive(PartialEq, Eq, Debug)]
struct PrivatePerson {
first_name: String,
last_name: String
}
}
但不适用于
with_generic! {
#[derive(PartialEq, Eq, Debug)]
struct MixedPerson {
pub first_name: String,
last_name: String
}
}
我想获得一些关于如何使宏在最后一种情况下工作的帮助。我觉得我可能在这里遗漏了一些基本的东西,例如用于绑定可见性的类型。如果有办法在获取字段名称和类型的同时绑定整个结构树,那也很好。
我还想了解如何让它与具有生命周期参数的结构一起工作,但也许这应该是一个单独的问题。
【问题讨论】:
标签: macros rust metaprogramming encapsulation