Assert equality of trait objects?

Viewed 431

The usual assert_eq! macro requires that PartialEq be implemented across a struct - I have a vector of trait objects, Vec<Box<dyn Element>>, where Element is a trait requiring Debug, pub trait Element: std::fmt::Debug. I cannot similarly require PartialEq as it requires Self as a type parameter, which the compiler cannot make into a trait object.

The solutions I've seen involve requiring an eq associated function in the trait definition, which doesn't appeal to me as this is just debug code, and I don't think it would be advantageous to include a method that would be a useless and potentially confusing addition to the trait's API outside of the cargo test build.

Is there any other (potentially unsafe) way to compare two trait objects?

1 Answers

Most probably you should implement whatever you need just for Debugging purposes. Check conditional compilation macros.

Anyway, since you already know they are Debug bound, you could try to use that as a comparison. Of course, you would need to tailor it properly.

fn compare_elements_by_debug_fmt<T>(e1: &T, e2: &T) -> std::cmp::Ordering
where 
    T: Debug,
{
    format!("{:?}", e1).cmp(&format!("{:?}", e2))
}

Playground

Related