Search code examples
rustrust-proc-macros

How do I check if a type implements a trait when implementing a proc macro?


I'm trying to create a proc-macro to derive and implement a trait for structs and I need that all fields within the struct implement Display.

How do I check that?

And furthermore how do I check if an attribute implements Iterator as well? (I want to handle if the item of the iterator implements display too).

I'm using syn and quote crates. And I managed to parse my struct and generate the implementation. But for types like Vec and Option I would like to check if they implement Iterator and handle it properly.

The syn::Field struct has the ty attribute which I believe should be a starting point, but looking into the docs I couldn't guess any way to check if this type implements a certain trait.


Solution

  • Add trait bounds and/or static assertions to the generated code. Macros run before type information is available since they can affect type information.