5

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?

  • Somehow you're going to need to resolve the question of how to compare `MyElement` to `YourElement` -- if comparing the `Debug` outputs is sufficient, that's fine, but in most cases where comparing values of different types makes sense, you're going to want something more similar to what's found at the linked question. – trent Mar 20 '21 at 14:50

1 Answers1

4

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

Netwave
  • 40,134
  • 6
  • 50
  • 93