rust - 如何在 Vector 上为我自己的结构实现 PartialEq?

标签 rust traits

我有以下定义:

pub struct List<T> {
    memory:  Vec<T>,
}

我会得到相当于 #[derive(PartialEq)] 的结果对于这种类型,如 How can I implement PartialEq? 中描述

我使用匹配表达式,例如:

impl<T: PartialEq> PartialEq for List<T> {
    fn eq(&self, other: &List<T>) -> bool {
        self.memory == other.memory      
    }
}
impl<T: fmt::Debug> fmt::Debug for List<T> where T:Display {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "["));
        for (count, v) in self.memory.iter().enumerate() {
            if count != 0 { try!(write!(f, ", ")); }
            try!(write!(f, "{}", v));
        }
        write!(f, "]")
    }
}
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);
    }
}

但是编译器给了我这些错误:

error: mismatched types [E0308]

if ! ( * left_val == * right_val ) {

note: in this expansion of assert_eq!

help: run rustc --explain E0308 to see a detailed explanation

note: expected type librusty_data_structures::List<u32>

note: found type [_; 4]

产生编译错误的main.rs

let mut listex: List<u32> = List::new();
listex.push(17);
listex.push(18);
listex.push(19);
listex.push(20);            
assert_eq!(listex, [17, 18, 19, 20]);

我不明白为什么这很重要。为什么它还要看那种类型?

最佳答案

listex[17, 18, 19, 20]具有不同的类型( List<u32>[_; 4] ),因此您无法检查它们的相等性。您需要更改 assert_eq!() 的参数之一的类型所以类型匹配。最简单的选择是引用 listexmemory :

assert_eq!(&listex.memory[0..4], [17, 18, 19, 20]);

或者您可以转换[17, 18, 19, 20]List<u32>这样PartialEq实现 List<T>可以付诸行动。

如果你要比较 listex与另一个List<32> ,你的PartialEq实现将允许检查相等性(尽管您需要 List<T> 派生 Debug 以便对它们执行 assert_eq!() )。

编辑:至于你的问题“为什么它甚至在看那种类型?”,请注意,在你的 PartialEq 的实现中:

fn eq(&self, other: &List<T>)

您指定 eq仅适用于 &List<T> 类型的两个参数( &self 指向 List<T> )。

关于rust - 如何在 Vector 上为我自己的结构实现 PartialEq?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39265755/

相关文章:

generics - 在不使用关联类型的情况下简化类型签名

scala - 在scala中的特征中初始化特征

selenium-webdriver - 需要一个字段作为 Rust 特征的一部分

rust - 以 &Box<T> 和 &T 作为参数的因式分解方法

types - isize 和 usize 的可用性如何,为什么它们有利于索引?

rust - 缓冲读取器缺少行的生命周期可防止拆分行

rust - 我们如何将 Rust 字符串转换为 gtk::type::String?

php - 我可以在特征中使用父类的属性吗?

rust - 为什么该特征没有实现?

rust - 缺少终身运营商