Deriving Traits in Rust with Procedural Macros

I just wrote a new blog post covering how to derive custom traits using procedural macros: Deriving Traits in Rust with Procedural Macros ·

I ran into some problems, and this works through that :slight_smile:

1 Like

Nice! It's good to see it built up step by step.
If you wanted to remove these:

extern crate quote;
extern crate syn;

you could do:

use quote::quote;
use syn::{parse_macro_input, DeriveInput};

I like to see where macros come from, though it has the caveat of being ambiguous: "am I importing a macro, or a module, or a function?"

1 Like

Nice post (good I learned about the generics.split_for_impl, I was trying to crunch the tokens manually and it is annoying and probably wrong).

Anyway, this feels like a bigger hammer than needed for the job. Did you know you can implement traits „en masse“?

impl<T: Template> WritableTemplate for T {
    fn write(&self, path: &Path) -> io::Result<()> {
        let mut file = io::BufWriter(fs::File::create(path)?);

1 Like

Yes, my bad for leaving them in. I got some helpful corrections on Reddit also that I'll make into GH issues on my blog repo so I'll try to get those changes shipped today.

Yes, this was also another thing I received in feedback on Reddit, basically using a where clause to automatically implement the trait for all askama::Template implementations. It's a big hammer, but there's another way to add a marker trait to be able to selectively implement the trait. It would have saved me some time if I remembered that it was possible to do this, but there wouldn't be a blog post so I guess it worked out :slight_smile:

Thanks everybody for the feedback and corrections, I have updated the post accordingly!