我正在使用 syn
解析 Rust 代码。当我使用 field.ty
读取命名字段的类型时,我得到了一个 syn::Type
。当我使用 quote!{#ty}.to_string()
进行打印时,我得到了 "Option<String>"
。
我该如何才能得到仅为 "String"
? 我想在 quote!
中使用 #ty
来打印出 "String"
而不是 "Option<String>"
。
我想生成以下代码:
impl Foo {
pub set_bar(&mut self, v: String) {
self.bar = Some(v);
}
}
从开始
struct Foo {
bar: Option<String>
}
我的尝试:let ast: DeriveInput = parse_macro_input!(input as DeriveInput);
let data: Data = ast.data;
match data {
Data::Struct(ref data) => match data.fields {
Fields::Named(ref fields) => {
fields.named.iter().for_each(|field| {
let name = &field.ident.clone().unwrap();
let ty = &field.ty;
quote!{
impl Foo {
pub set_bar(&mut self, v: #ty) {
self.bar = Some(v);
}
}
};
});
}
_ => {}
},
_ => panic!("You can derive it only from struct"),
}
Option<T>
连接回到T
,例如:impl<T> MyTrait for Option<T> { type Assoc = T; }
。然后,您的宏可以扩展为set_bar(&mut self, v: <Option<String> as MyTrait>::Assoc)
。 - trent