实现PartialEq以比较不同特征的对象

时间:2018-05-30 23:05:42

标签: rust traits

我试图以允许我测试类型之间的相等性的方式实现一组特征。我跟着How to test for equality between trait objects?。我可以使用tr_eq方法在类型之间进行测试,但我无法使==运算符起作用。我在这里做错了什么?

use std::any::Any;
use std::fmt::Debug;

pub trait Obj<'a>: Debug + Any {
    fn as_any(&self) -> &Any;

    fn tr_eq(&self, other: &Obj) -> bool;
}

impl<'a> Obj<'a> for bool {
    fn as_any(&self) -> &Any {
        self
    }

    fn tr_eq(&self, other: &Obj) -> bool {
        other
            .as_any()
            .downcast_ref::<bool>()
            .map_or(false, |a| self == a)
    }
}

impl<'a> PartialEq for Obj<'a> {
    fn eq(&self, other: &Obj) -> bool {
        self.tr_eq(other)
    }
}

#[derive(Debug, PartialEq)]
pub struct Marker;

impl<'a> Obj<'a> for Marker {
    fn as_any(&self) -> &Any {
        self
    }

    fn tr_eq(&self, other: &Obj) -> bool {
        other
            .as_any()
            .downcast_ref::<Marker>()
            .map_or(false, |a| self == a)
    }
}

fn main() {
    println!("true == Marker: {:?}", true == Marker {}); // error
    println!("true == true: {:?}", true == true);
    println!(
        "&true as &Obj == &Marker as &Obj: {:?}",
        &true as &Obj == &Marker {} as &Obj
    );
    println!("Marker.tr_eq(&true): {:?}", Marker {}.tr_eq(&true));
    println!(
        "&Marker as &Obj == (&true as &Obj): {:?}",
        &Marker {} as &Obj == (&true as &Obj)
    );
    println!("false.tr_eq(&true): {:?}", false.tr_eq(&true));
    println!("true.tr_eq(&true): {:?}", true.tr_eq(&true));
    println!("Marker==Marker: {:?}", Marker {} == Marker {})
}
error[E0308]: mismatched types
  --> src/main.rs:47:46
   |
47 |     println!("true == Marker: {:?}", true == Marker {});
   |                                              ^^^^^^^^^ expected bool, found struct `Marker`
   |
   = note: expected type `bool`
              found type `Marker`

0 个答案:

没有答案