Providing additional constraint on type

I have the following code (playground):

trait Animal: std::fmt::Debug {}

trait Zoo {
    fn animals(&self) -> Vec<Box<dyn Animal>>;
}

impl Zoo for String {
    fn animals(&self) -> Vec<Box<dyn Animal>> {
        todo!()
    }
}

fn test() {
    assert_eq!("".to_string().animals(), vec![]);
}

The last line assert_eq!("".to_string().animals(), vec![]); fails to compile (binary operation ==cannot be applied to typeVec<Box>``). I believe this is because there is no constraint of PartialEquality on the elements returned from animals(). But I am not sure how to specify one. How do I express a constraint something along the lines of dyn Animal + PartialEq?

Note that in my real program the equivalent of the Animal type comes from a different crate and thus cannot be modified.

Comparing trait objects is pretty tricky and requires some dynamic dispatch tricks and downcasting. Here's one way to do it (playground).

2 Likes

Thank you so much. It fits my needs perfectly!