Apply Procedural Macros on third party structs

I wrote a procedural macro which can add impl MyTrait for the given struct, but some of the struct are not written by me (third party codes), for example:

// third party struct in Foo.rs
struct Foo {
    
}

// main.rs
#[derive(MyMacro)]
struct Foo;

How can I do that?

Generally you can't do that directly, not for some type T defined outside of your crate.

But what you can do is newtype T, implement your functionality for that type, and implement Deref<Target = T> so you can still access the functionality provided by T.

Usually, we apply a derive macro on a struct to implement traits, which has a high chance to violate the orphan rules if the struct is a third party struct.

I realized that prevent a derive macro from applying on a third party struct directly sound reasonable.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.