I'm working on a Rust project where I have a trait defined with pub(crate)
visibility. When I try to implement a foreign trait for types that implement my local, crate-private trait, the compiler complains about violating the orphan rule. Here's a minimal example:
// Inside my crate
pub(crate) trait MyLocalTrait {
// ...
}
// serde is a dependency, so Serialize is a "foreign" trait
impl<T: MyLocalTrait> serde::Serialize for T {
// ...
}
My understanding is that since MyLocalTrait
is only visible within my crate, the only types that could implement it would also have to be local. Shouldn't this be enough to satisfy the orphan rule, since there's no chance of a foreign type implementing MyLocalTrait
? Is this a limitation in the current implementation of the orphan rule, or is there something I'm missing?
After thinking about it for a little bit, it became obvious why this is not allowed. While pub(crate)
makes is so that a foreign crate can't implement MyLocalTrait
, that doesn't exclude my local crate from implementing it for a foreign type:
// Inside my crate
pub(crate) trait MyLocalTrait {
// ...
}
// Also inside my crate
impl MyLocalTrait for SomeForeignType {
// ...
}
// Error because `serde::Serialize` is now implemented for `SomeForeignType`, violating the orphan rule
impl<T: MyLocalTrait> serde::Serialize for T {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With