我有一个结构,它全部存储只读引用,例如:
struct Pt { x : f32, y : f32, }
struct Tr<'a> { a : &'a Pt }
我想impl Eq
让Tr
测试底层的a
引用是否完全相同Pt
:
let trBase1 = Pt::new(0.0, 0.0);
let trBase2 = Pt::new(0.0, 0.0);
assert!(trBase1 == trBase2); // ok.
let tr1 = Tr::new(&trBase1);
let tr2 = Tr::new(&trBase2);
let tr3 = Tr::new(&trBase1);
assert!(tr1 == tr3); // ok.
assert!(tr1.a == te2.a); // ok. Using Eq for Pt that compare values.
assert!(tr1 != tr2); // panicked! Not intended.
现在我有
impl<'a> PartialEq for Tr<'a> {
fn eq(&self, v : &Tr<'a>) -> bool {
// self.a == v.a // doesn't work.
}
}
我应该写什么?
答案 0 :(得分:5)
您可以使用std::ptr::eq
比较两个指针的地址。如果引用(&T
或&mut T
)被馈送到该函数,则它们将自动强制转换为基础指针(*const T
)。当然,可变引用与另一个引用具有相同的地址是没有意义的,因为可变引用始终是互斥引用,但仍可以强制使用*const T
。
// This derive will use the equality of the underlying fields
#[derive(PartialEq)]
struct Pt {
x: f32,
y: f32,
}
impl Pt {
fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
}
struct Tr<'a> {
a: &'a Pt,
}
impl<'a> Tr<'a> {
fn new(a: &'a Pt) -> Self {
Self { a }
}
}
// Here we use std::ptr::eq to compare the *addresses* of `self.a` and `other.a`
impl<'a> PartialEq for Tr<'a> {
fn eq(&self, other: &Tr<'a>) -> bool {
std::ptr::eq(self.a, other.a)
}
}
fn main() {
let tr_base1 = Pt::new(0.0, 0.0);
let tr_base2 = Pt::new(0.0, 0.0);
assert!(tr_base1 == tr_base2);
let tr1 = Tr::new(&tr_base1);
let tr2 = Tr::new(&tr_base2);
let tr3 = Tr::new(&tr_base1);
assert!(tr1 == tr3);
assert!(tr1.a == tr2.a);
assert!(tr1 != tr2);
}
答案 1 :(得分:1)
将引用转换为原始指针并进行比较。
impl<'a> PartialEq for Tr<'a> {
fn eq(&self, v: &Tr<'a>) -> bool {
self.a as *const _ == v.a as *const _
}
}