我想比較Obj
只有當它們是從相同的Parent
對象創建時,它才起作用,但只有一種方法:如果切換比較順序,它不會。如何比較對象,只有當它們是從同一個父對象創建的時候?
下面是最少的代碼:
struct Parent {
val: u64,
}
impl Parent {
pub fn new(v: u64) -> Parent {
Parent { val: v }
}
pub fn child(&self, v: u64) -> Child {
Child {
val: v,
phantom: PhantomData,
}
}
}
struct Child<'a> {
val: u64,
phantom: PhantomData<&'a Parent>,
}
impl<'a> Child<'a> {
pub fn compare(&'a self, l: &Obj<'a>, r: &Obj<'a>) -> bool {
l.val == r.val
}
pub fn obj(&'a self, v: u64) -> Obj<'a> {
Obj {
val: v,
child: self,
}
}
}
struct Obj<'a> {
val: u64,
child: &'a Child<'a>,
}
impl<'a> PartialEq<Obj<'a>> for Obj<'a> {
fn eq(&self, other: &Obj<'a>) -> bool {
self.child.compare(self, other)
}
}
#[test]
fn test() {
let parent = Parent::new(1);
let child = parent.child(2);
let obj1 = child.obj(3);
let obj2 = child.obj(3);
// those are from the same parent, this sould work (and works).
assert!(obj1 == obj2);
assert!(obj2 == obj1);
let parent2 = Parent::new(1);
let child2 = parent2.child(2);
let obj12 = child2.obj(3);
let obj22 = child2.obj(3);
// this works fine too
assert!(obj12 == obj22);
assert!(obj22 == obj12);
// those are from different parents
// assert!(obj1 == obj12); // that line DOES NOT compile, which is exactly what I want!
assert!(obj12 == obj1); // but that line suddenly DOES compile.
}
所以,問題是:如何修復代碼,使最後一行將無法編譯?
我不認爲壽命分別爲編碼的正確方法。由於第二個父代是在第一個父代之後定義的,因此它的生命週期嚴格在第一個父代的生命週期內。你可以想到的任何生命週期檢查仍然允許任何具有第二生命週期的對象在需要第一生命週期的情況下使用 –