I'm trying to create a derive macro in Rust to create instances, as an example, which should implement following trait:
pub trait MyTrait { fn my_default() -> Option<Self>; } I use syn and quote to parse and generate the AST, as following:
#[proc_macro_derive(MyTrait)] pub fn my_default_derive(input: TokenStream) -> TokenStream { // Use `syn` to parse // ... let gen = quote! { impl #impl_generics_strait::MyTrait for #name #ty_generics #where_clause { fn my_default() -> Option<Self>{ // ... } } }; gen.into() } As the compiler doest not know what Self is at compile time, foregoing will cause error:
the size for values of type `Self` cannot be known at compilation time My questions are:
- Is it possible to use Self in
proc_macro_derive? - How?
BTW, I'm trying to use ident instead, and will post progress here later.
Update:
- It turns out, the error is caused by the trait declaration, not the
proc_macro_derive. To fix,Sizedshould be added to the trait name.
: Sizedbound on its declaration.