我正在尝试使用 Rust 中的过程宏来生成一个常量,其中包含与命名结构的字段相同的静态字符串切片切片。例如对于
struct MyStruct {
a: u8,
b: u8,
}
我想输出类似的东西
impl MyStruct {
pub const FIELD_NAMES: &'static [&'static str] = ["a", "b"];
}
这可以使用声明性宏来完成,如下所示:
macro_rules! field_names {
(struct $name:ident {
$($field_name:ident: $field_type:ty,)*
}) => {
struct $name {
$($field_name: $field_type,)*
}
impl $name {
pub const LIST: &'static [&'static str] = &[$(stringify!($field_name)),*];
}
}
}
field_names! {
struct MyStruct {
a: u8,
b: u8,
}
}
但是,我找不到对程序宏执行类似操作的方法-有这样的方法吗?程序会比命令式更好,因为命令式宏的当前实现不允许泛型等,并且添加它会使其变得非常复杂。
[编辑]:我已经设法为结构获得了 proc_macro2::Ident
的迭代器,但我不知道如何将其转换为常量切片。