rust - 如何在 Rust 过程宏中获取 impl 块的类型?
问题描述
我正在尝试编写一个可以应用于这样的 impl 块的 Rust 过程宏;
struct SomeStruct { }
#[my_macro]
impl SomeStruct { }
我正在使用 syn 和 quote 来解析和格式化TokenStream
宏中的 s。它看起来像这样:
#[proc_macro_attribute]
pub fn my_macro(meta: TokenStream, code: TokenStream) -> TokenStream {
let input = parse_macro_input!(code as ItemImpl);
// ...
TokenStream::from(quote!(#input))
}
有没有办法使用 syn 访问 impl 块的类型名称?我没有看到任何ItemImpl
可以为我提供该信息的字段。
解决方案
该文档列出了 9 个字段ItemImpl
:
attrs: Vec<Attribute>
defaultness: Option<Default>
unsafety: Option<Unsafe>
impl_token: Impl
generics: Generics
trait_: Option<(Option<Bang>, Path, For)>
self_ty: Box<Type>
brace_token: Brace
items: Vec<ImplItem>
其中只有一个有“类型”这个词:self_ty
.
use syn; // 0.15.23
fn example(input: syn::ItemImpl) {
println!("{:#?}", input.self_ty);
}
fn main() {
let code = syn::parse_str(
r###"
impl Foo {}
"###,
)
.unwrap();
example(code);
}
Path(
TypePath {
qself: None,
path: Path {
leading_colon: None,
segments: [
PathSegment {
ident: Ident(
Foo
),
arguments: None
}
]
}
}
)
推荐阅读
- python - 为什么 `dataclasses.asdict(obj)` > 10x 比 `obj.__dict__()` 慢
- python - ModuleNotFoundError:尝试 docker-compose 时没有名为“wtforms”的模块
- python - Python程序不应该计算浮点长度,只计算字符串
- android - 在 Android Studio 中将查询参数添加到 Retrofit get
- symfony - 实体 symfony 中的参考设置值
- c - 排序程序 C 中的分段错误
- kubernetes - Kubernetes POD 自动化 - 根据旧部署的成功完成安排新部署
- python - Django 管理命令参数
- function - f#上二叉树的前序遍历
- java - Java中基于优先级的文件数据更新和多线程