简体   繁体   English

为什么 Rust 阻止为外部结构实现外部特征?

[英]Why does Rust prevent implementing an external trait for an external struct?

I just came across the problem of implementing a trait I do not own for a type I do not own.我刚刚遇到了为我不拥有的类型实现我不拥有的特征的问题。 Then I googled the exact How do I implement a trait I don't own for a type I don't own?然后我用谷歌搜索了我如何为我不拥有的类型实现我不拥有的特征? question.问题。

The thing that confused me is the motivation behind such restriction.让我感到困惑的是这种限制背后的动机。 I came from Scala where it is possible to have an external typeclass instance for an external type.我来自 Scala,在那里可以有一个外部类型的外部类型实例。

Why does Rust restrict that?为什么 Rust 会限制它?

As Alexey Larionov explains in the comments, if two crates could implement a trait for the same struct there would be a conflict of which trait implementation to use.正如 Alexey Larionov 在评论中解释的那样,如果两个 crate 可以为同一个结构实现一个 trait,那么使用哪个 trait 实现就会发生冲突。 With this restriction, Rust guarantees that every (struct, trait) pair will have at most one implementation across all crates.有了这个限制,Rust 保证每个 (struct, trait) 对在所有 crate 中最多有一个实现。

If you find yourself needing to implement an external trait for an external struct you can leverage the Rust New Type Idiom .如果您发现自己需要为外部结构实现外部特征,您可以利用Rust New Type Idiom

By wrapping an external struct in a new type you are able implement any external trait on that new type.通过将外部结构包装在新类型中,您可以在该新类型上实现任何外部特征。

While the new type won't be the same as the external struct, you can reference that wrapped type with the .0 syntax, as explained in the New Type Idiom documentation.虽然新类型与外部结构不同,但您可以使用.0语法引用该包装类型,如 New Type Idiom 文档中所述。

I just read the Rust Book 's chapter about implementing traits and, as @AlexLarionov suggested in the comment that it would be impossible to choose an appropriate implementation:我刚刚阅读了Rust Book关于实现特征的章节,正如@AlexLarionov 在评论中建议的那样,不可能选择合适的实现:

But we can't implement external traits on external types.但是我们不能在外部类型上实现外部特征。 For example, we can't implement the Display trait on Vec<T> within our aggregator crate, because Display and Vec<T> are defined in the standard library and aren't local to our aggregator crate.例如,我们不能在我们的聚合器板条箱中实现Vec<T>Display特征,因为DisplayVec<T>是在标准库中定义的,并且不是我们的聚合器板条箱本地的。 This restriction is part of a property of programs called coherence, and more specifically the orphan rule, so named because the parent type is not present.这个限制是程序属性的一部分,称为连贯性,更具体地说是孤儿规则,之所以这样命名是因为父类型不存在。 This rule ensures that other people's code can't break your code and vice versa.此规则确保其他人的代码不会破坏您的代码,反之亦然。 Without the rule, two crates could implement the same trait for the same type, and Rust wouldn't know which implementation to use.如果没有这个规则,两个 crate 可以为相同的类型实现相同的 trait,并且 Rust 不知道使用哪个实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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