[英]How to hide trait implementation in Rust
I have a project with its own error type, which is exposed outside of crate.我有一个项目有自己的错误类型,它暴露在 crate 之外。 Lets call it
MyErrorType
.让我们称之为
MyErrorType
。 The project itself internally depends on another crate with its own error type.项目本身在内部依赖于另一个具有自己错误类型的 crate。 Lets call it
ForeignErrorType
.让我们称之为
ForeignErrorType
。
In order to simplify code and make it more readable I've created following implementation of From trait:为了简化代码并使其更具可读性,我创建了From特征的以下实现:
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.问题是提到的 trait 实现暴露在我的 crate 之外。 I don't want the users of my crate to accidentally rely on the conversion possibility from
ForeignErrorType
to MyErrorType
.我不希望我的箱子的用户意外地依赖从
ForeignErrorType
到MyErrorType
的转换可能性。
What I've tried so far: Have put the mentioned trait implementation into module with pub(crate)
visibility.到目前为止我已经尝试过:已将提到的特征实现放入具有
pub(crate)
可见性的模块中。 This surprisingly hides all struct
s defined in such module, but leaves trait implementation exposed.这令人惊讶地隐藏了此类模块中定义的所有
struct
,但暴露了 trait 实现。
From
implementation private and not to expose it outside of crate?From
实现私有而不是将它暴露在 crate 之外??
?
operator on foreign error types without exposing them?Is there way to keep my
From
implementation private and not to expose it outside of crate?有没有办法让我的
From
实现私有而不是将它暴露在 crate 之外?
No. Trait implementations have no scope.没有。特征实现没有 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 ?
在这种情况下,您可以做的是编写一个 function ,其内容与您的
From
实现的内容相同,然后在Result::map_err
之前应用它?
. .
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.用法,但是没有办法进行范围为 crate 或模块的隐式转换,所以这是你可以拥有的最好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.