Cryptor
Cryptor

Reputation: 357

How to hide trait implementation in Rust

I have a project with its own error type, which is exposed outside of crate. Lets call it MyErrorType. The project itself internally depends on another crate with its own error type. Lets call it ForeignErrorType.

In order to simplify code and make it more readable I've created following implementation of From trait:

impl From<ForeignErrorType> for MyErrorType {
   ...
}

This allows to use question mark operator, ?, when dealing with foreign error types without a necessity to convert them in place.

The issue is that the mentioned trait implementation is exposed outside of my crate. I don't want the users of my crate to accidentally rely on the conversion possibility from ForeignErrorType to MyErrorType.

What I've tried so far: Have put the mentioned trait implementation into module with pub(crate) visibility. This surprisingly hides all structs defined in such module, but leaves trait implementation exposed.

Upvotes: 3

Views: 983

Answers (1)

Kevin Reid
Kevin Reid

Reputation: 43753

Is there way to keep my From implementation private and not to expose it outside of crate?

No. Trait implementations have no scope.

What you can do instead in this case is write a function with the same contents as your From implementation would have had, and apply it with Result::map_err before ?.

pub(crate) fn foreign_err(e: ForeignErrorType) -> MyErrorType {
    todo!()
}

...

let foo = their_function().map_err(foreign_err)?;

This has to be done at every ? usage, but there is no way to have an implicit conversion that is scoped to a crate or module, so that's the best you can have.

Upvotes: 3

Related Questions