0

When I use the Serialize macro of serde I use the Macro and Trait together so I don't need to import the trait additional.

#[serde::Serialize)]
struct Abc {
  a: 4
}

How does it work? When I try to implement this, I can't find a working solution and I can't find something about this in the internet.

Here is a snippet, what I found in the serde logic to get this functionality

pub mod traits;

pub use traits::Example;

#[cfg(feature = "lib_derive")]
#[macro_use]
extern crate lib_derive;
#[cfg(feature = "lib_derive")]
pub use lib_derive::Example;

In this case the compiler throws an error with the note: this error originates in the derive macro 'lib::Example', so it didn't find the Trait, but in the serde crate it works.

What did I miss here?

Corfus
  • 13
  • 4

1 Answers1

0

I understand the problem now and the note of the compiler.

You have to add the path to the type in your macro in the crate, then it works great like expected, if you forgot this you have to add use lib::Example;, to specify your trait because it isn't known in the scope.

With this example it works.

#[proc_macro_derive(Example)]
pub fn example_derive(input: TokenStream) -> TokenStream {
  let ast = syn::parse(input).unwrap();
    impl_example_macro(&ast)
}

fn impl_example_macro(ast: &syn::DeriveInput) -> TokenStream {
  let name = &ast.ident;
  let gen = quote! {
        impl lib::Example for #name {
            fn example(&self) {}
        }
    };
  gen.into()
}
Corfus
  • 13
  • 4