我有以下定义:
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 explanationnote: 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!()
的参数之一的类型所以类型匹配。最简单的选择是引用 listex
的memory
:
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/