Is it possible to restrict the visibility of a trait implementation?
For example, if I implement DerefMut or IndexMut on a public type, can I keep the implementations private to the crate?
The visibility of a trait implementation is the intersection of the visibility of the trait and the visibility of the type it's implemented on.
You can't do exactly that; as @jethrogb says, since the type is public, and DerefMut
is public, the impl will be visible. However, you could make the public type a "newtype" of a private type that implements DerefMut
and IndexMut
:
mod my_module {
pub struct PublicType(PrivateType);
struct PrivateType { ... actual stuff ... }
impl DerefMut for PrivateType { ... }
...
}
Since PrivateType
isn't pub
, and the sole element of PublicType
isn't pub
, there's no way for code outside my_module
to get at a PrivateType
instance and use its DerefMut
implementation. This comes at the cost of methods on PublicType
that simply forward the operation to self.0
.
Thanks! That's pretty much what I had figured out, but I wanted to be sure.
That's not terribly convenient, it adds yet a little more boilerplate and type and method wrappings. It's a shame that we can control the visibility of the methods but not implement things like IndexMut
that can be quite convenient and keep them private.
You could add another Deref implementation for PublicType to PrivateType. This will make internal usage more ergonomic.
Yeah that's probably as close as I'll get to what I wanted. Thanks