如何为我的struct实现PartialEq和反向PartialEq

时间:2017-05-18 07:13:41

标签: rust

我根据this post

提出的解决方案,为Vec提供了PartialEq这个结构
pub struct List<T> {
    memory:  Vec<T>,
}

impl<T> List<T> {
    pub fn new() -> Self {
        List {
            memory: Vec::new(),
        }
    }
    // push() add to end of list
    pub fn push(&mut self, value: T) {
        self.memory.push(value);
    }
}

impl<T, U> PartialEq<U> for List<T>
    where Vec<T>: PartialEq<U>
{
    fn eq(&self, other: &U) -> bool {
        &self.memory == other
    }
}

impl<T> PartialEq<List<T>> for Vec<u32>
    where T: PartialEq<u32>
{
    fn eq(&self, other: &List<T>) -> bool {
        &other.memory == self
    }
}

/* COMMENTED BECAUSE IT DOESN'T COMPILE
impl<T, U> PartialEq<List<T>> for Vec<U>
    where T: PartialEq<U>
{
    fn eq(&self, other: &List<T>) -> bool {
        &other.memory == self
    }
}
*/

fn main() {
    let mut listex: List<u32> = List::new();

    listex.push(17);
    listex.push(18);
    listex.push(19);
    listex.push(20);            

    println!("{}", listex == vec![17, 18, 19, 20]);
    println!("{}", vec![17, 18, 19, 20] == listex);
}

它编译和工作

    Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/tests`
true
true

但要实现反向==(即能够同时执行listex == vec![1,2]vec![1,2] == listex),我必须为PartialEq专门实施Vec<u32>并且可以我使用通用参数,因为我得到以下编译器错误(取消注释PartialEq<List<T>> for Vec<U>集团)

error[E0210]: type parameter `U` 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
  --> src/main.rs:25:1
   |
25 | / impl<T, U> PartialEq<List<T>> for Vec<U>
26 | |     where T: PartialEq<U>
27 | | {
28 | |     fn eq(&self, other: &List<T>) -> bool {
29 | |         &other.memory == self
30 | |     }
31 | | }
   | |_^

除了宏,是否有一种有效的方法来实现所有(或许多)可能的PartialEq以启用反向PartialEq?

0 个答案:

没有答案