简体   繁体   English

全面实施受本地定义的公共性状约束的核心性状

[英]Blanket implementation of core traits constrained by locally-defined public trait

I have the following code: 我有以下代码:

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

I get the following error: 我收到以下错误:

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 | | }
   | |_^

Why? 为什么? I haven't implemented GetIdentifier for &_ , so the blanket impl shouldn't apply to &_ . 我还没有实现GetIdentifier&_ ,所以毯impl不应适用于&_ Consumers of my crate wouldn't be able to implement GetIdentifier for core types either, so no problem there. 我的板条箱的消费者也无法为核心类型实现GetIdentifier ,因此在那里没有问题。 What am I missing here? 我在这里想念什么? Why is &_ even involved here -- I didn't put an ?Sized bound on my trait so references shouldn't even be considered....right? 为什么&_甚至参与到这里-我没有在特征上加上?Sized限制,因此甚至不应考虑引用...。

Consumers of your crate might implement GetIdentifier for TheirType and simultaneously implement Hash for TheirType . 您的板条箱的使用者可以为TheirType GetIdentifier实现TheirType ,同时为他们的TheirType实现Hash

Now you might say that's their problem, but imagine another crate with a trait Foo that also does impl<T: Foo> Hash for T {} , and TheirType implementing Foo and GetIdentifier . 现在,您可能会说这是他们的问题,但是想象一下另一个具有特征Foo板条箱,它也impl<T: Foo> Hash for T {} TheirType impl<T: Foo> Hash for T {} ,并且他们的TheirType实现了FooGetIdentifier Suddenly they can't implement either trait. 突然,他们无法实现任何一个特征。

The reason the error occurs for &_ is that the stdlib impl says any type T implementing Hash causes &T to also implement Hash . 对于&_发生错误的原因是stdlib impl表示任何实现Hash类型T都会导致&T也实现Hash

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

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