【问题标题】:Blanket implementation of core traits constrained by locally-defined public trait受本地定义的公共特征约束的核心特征的一揽子实现
【发布时间】:2017-05-03 14:50:42
【问题描述】:

我有以下代码:

pub trait GetIdentifier {
    //...
}
impl<T: GetIdentifier> Hash for T {
     fn hash(&self) -> //....
}

我收到以下错误:

error[E0119]: conflicting implementations of trait `std::hash::Hash` for type `&_`:
  --> <anon>:18:1
   |
18 | / impl<T: GetIdentifier> Hash for T {
19 | | }
   | |_^
   |
   = note: conflicting implementation in crate `core`

error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`); only traits defined in the current crate can be implemented for a type parameter
  --> <anon>:18:1
   |
18 | / impl<T: GetIdentifier> Hash for T {
19 | | }
   | |_^

为什么?我还没有为&amp;_ 实现GetIdentifier,所以毯子impl 不应该适用于&amp;_。我的箱子的消费者也不能为核心类型实现GetIdentifier,所以没有问题。我在这里想念什么?为什么&amp;_ 甚至涉及到这里——我没有在我的 trait 上设置 ?Sized 绑定,所以甚至不应该考虑引用......对吗?

【问题讨论】:

    标签: rust traits


    【解决方案1】:

    您的 crate 的使用者可以为 TheirType 实现 GetIdentifier,同时为 TheirType 实现 Hash

    现在您可能会说这是他们的问题,但想象另一个具有 Foo 特征的板条箱,它也执行 impl&lt;T: Foo&gt; Hash for T {}TheirType 实现 FooGetIdentifier。突然他们无法实现这两个特征。

    &amp;_ 发生错误的原因是 stdlib impl 说任何类型 T 实现 Hash 导致 &amp;T 也实现 Hash

    【讨论】:

    • 据我了解,OP 声明 GetIdentifier 是本地特征,因此无法从外部实现。
    • 我认为 trait 是公开的,否则不需要区分核心类型和自定义类型
    • @E_net4 我的意思是本地定义的公共特征——我会更新问题
    • 这是有道理的——后续问题:如果特征是私有的,我仍然得到错误。这是有原因的,还是有一些规则说标记private trait public 不应该导致代码无法编译?
    • 可见性没有任何改变,因为通过某种间接或其他方式,您最终可能会遇到同样的问题。 Rust 不做任何全局分析。从某种意义上说,所有分析都是局部的。
    猜你喜欢
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 2019-12-08
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多