#Orphan Rule and Proc Macros

10 messages · Page 1 of 1 (latest)

red citrus
#

Is it possible to add a proc macro for code that you don't own? for example is there a way i could add a derive macro to some pub struct from another crate? like if i wanted some fn to be called at the beginning of any of the serialize funtions is it even possible to put a derive macro on this struct?

https://docs.rs/serde_json/latest/serde_json/struct.Serializer.html

or maybe there's a trick with newtype to do this?

copper stone
#

Serde in particular does support this

copper stone
#

Look into its "remote derive" feature

#

However, there is no general solution. The derive has to support it

#

Before you use remote derives, check if the crate has a serde feature, or something related, to turn on derives of their own

red citrus
#

ah, interesting. I wouldnt have guessed that from the name, but thats really cool.

But as a general answer to the question, that's not something you can usually do, but serde (and some other crates) do allow that?

copper stone
#

Serde has a slightly weird API for it: it makes you write a copy of the foreign type, put the derive on the copy, and say "this is actually meant to implement for (a newtype around) the foreign type".

#

It makes sense owing to the limits of what macros can see: only their input.

#

But it does require some extra work, so it's not that common