0

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, Sized should be added to the trait name.
7
  • 3
    This has nothing to do with macros. Commented Aug 1, 2019 at 8:01
  • You can make your trait work by adding a : Sized bound on its declaration. Commented Aug 1, 2019 at 8:02
  • @mcarton Yeah, you are right. Commented Aug 1, 2019 at 8:25
  • @hxpax in this situation, will you close the question or self answer it or waiting for someone to write answer to approve? Commented Aug 1, 2019 at 11:21
  • 1
    This strikes me as a "can not be reproduced" kind of question because, although not a typo, it's based on a mistaken premise (that the error has something to do with macros) and was resolved in a way unlikely to help future readers. It could probably be marked instead as a dupe of some other question, possibly this one. Commented Aug 1, 2019 at 14:42

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.