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.
Galaxy
  • 1,129
  • 11
  • 27
  • 3
    This has [nothing to do with macros](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7638ef7b828950991b75da7c11d1db7e). – mcarton Aug 01 '19 at 08:01
  • You can make your trait work by [adding a `: Sized` bound on its declaration](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=024fa70253de0de29bf83675141cc525). – mcarton Aug 01 '19 at 08:02
  • @mcarton Yeah, you are right. – Galaxy Aug 01 '19 at 08:25
  • @hxpax in this situation, will you close the question or self answer it or waiting for someone to write answer to approve? – Akiner Alkan Aug 01 '19 at 11:21
  • @Websterix Tried to close, but could not find out a proper reason item. Will anwser it myself if mcarton do not. – Galaxy Aug 01 '19 at 11:26
  • 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](https://stackoverflow.com/q/54465400/3650362). – trent Aug 01 '19 at 14:42
  • Possible duplicate of [Why does returning \`Self\` in trait work, but returning \`Option\` requires \`Sized\`?](https://stackoverflow.com/questions/54465400/why-does-returning-self-in-trait-work-but-returning-optionself-requires) – Galaxy Aug 02 '19 at 06:58

0 Answers0