I'm using syn
to parse Rust code. When I read a named field's type using field.ty
, I get a syn::Type
. When I print it using quote!{#ty}.to_string()
I get "Option<String>"
.
How can I get just "String"
? I want to use #ty
in quote!
to print "String"
instead of "Option<String>"
.
I want to generate code like:
impl Foo {
pub set_bar(&mut self, v: String) {
self.bar = Some(v);
}
}
starting from
struct Foo {
bar: Option<String>
}
My attempt:
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>
back toT
by using a trait, for example:impl<T> MyTrait for Option<T> { type Assoc = T; }
. Then your macro can expand toset_bar(&mut self, v: <Option<String> as MyTrait>::Assoc)
– Blaise