简体   繁体   English

如何在 Rust 中隐藏特征实现

[英]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 .我不希望我的箱子的用户意外地依赖从ForeignErrorTypeMyErrorType的转换可能性。

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 实现。

  • Is there way to keep my From implementation private and not to expose it outside of crate?有没有办法让我的From实现私有而不是将它暴露在 crate 之外?
  • Probably I'm trying to achieve error handling benefits in a non‑idiomatic way.可能我正试图以非惯用的方式实现错误处理的好处。 If this is true, what's the proper way to be able to use ?如果这是真的,那么正确的使用方法是? 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM