我有这个问题:
- 多个结构体实现了一个trait
Event
- 所有的结构体都可以用相同的方式实现
PartialEq
trait
我考虑写成这样(简短版)
type Data = Vec<u8>;
trait Event {
fn data(&self) -> &Data;
}
struct NoteOn {
data: Data,
}
struct NoteOff {
data: Data,
}
impl Event for NoteOn {
fn data(&self) -> &Data {
&self.data
}
}
impl Event for NoteOff {
fn data(&self) -> &Data {
&self.data
}
}
impl<T: Event> PartialEq for T {
fn eq(&self, b: &T) -> bool {
self.data() == b.data()
}
}
fn main() {
println!("Hello, world!");
}
这段代码编译失败:
error[E0119]: conflicting implementations of trait `std::cmp::PartialEq<&_>` for type `&_`:
--> src/main.rs:23:1
|
23 | impl<T: Event> PartialEq for T {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: conflicting implementation in crate `core`:
- impl<A, B> std::cmp::PartialEq<&B> for &A
where A: std::cmp::PartialEq<B>, A: ?Sized, B: ?Sized;
= note: downstream crates may implement trait `Event` for type `&_`
error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> src/main.rs:23:1
|
23 | impl<T: Event> PartialEq for T {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type parameter `T` must be used as the type parameter for some local type
|
= note: only traits defined in the current crate can be implemented for a type parameter
这里有什么问题吗? 或者是否有另一种实现通用的方式可以避免为 NoteOn 和 Noteff 都重复输入 PartialEq? 谢谢。
enum
代替trait,或者为trait对象类型实现PartialEq
。 - trentEvent
不相关;你没有拥有PartialEq
或T
(对于某个假设的T
),因此你不能为T
实现PartialEq
。 - trent