Comparing trait objects

I want to compare two trait objects. If they're the same trait implementation, apply PartialEq to the items, otherwise false. Rust won't derive PartialEq for a trait, which would be nice. So

trait Viewable {
   fn is_same(&self, other: &dyn Viewable) -> bool;
}

#[derive (PartialEq)]
struct SculptData {
}

impl Viewable For SculptData {
    fn is_same(&self, other: &dyn Viewable) -> bool {
       self == other // can't do that, of course
    }
}

So, how to do this? Do I have to go through the whole Any/downcast thing, or is there some automation for this?

Do you mean that they are the same type? Then you should probably add an Any bound (and an explicit conversion method to &dyn Any in the absence of supertrait coercions), and use <dyn Any>::downcast_ref::<Self>() to check whether other has the same type as self. Playground

Note that this won't work transitively, since a trait object (as a concrete type) itself can still be wrapped into another level of trait objects, so this might not always work as expected.

I wouldn't be surprised if there's a crate for this, but it came up in this thread and I threw together a PoC which may be useful.

I know how to do it the hard way. I was hoping for an easy way. Like being able to derive PartialEq for traits and getting all that machinery generated.

Built in? No. This crate exists.

That worked great. Thanks.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.