断言特征对象的相等性?

问题描述

通常的 assert_eq! 宏要求 PartialEq 跨结构实现 - 我有一个特征对象向量 Vec<Box<dyn Element>>,其中 Element 是需要调试的特征,pub trait Element: std::fmt::Debug。我不能类似地要求 PartialEq,因为它要求 Self 作为类型参数,编译器无法将其转换为 trait 对象。

我看到的解决方案涉及在 trait 定义中需要一个 eq 关联函数,这对我没有吸引力,因为这只是调试代码,我认为包含一个方法没有好处是 cargo test 构建之外的特征 API 的无用且可能令人困惑的补充。

是否还有其他(可能不安全的)方法来比较两个 trait 对象?

解决方法

很可能你应该实现任何你需要的只是为了调试目的。检查conditional compilation macros

无论如何,由于您已经知道它们是 Debug 绑定的,因此您可以尝试将其用作比较。当然,您需要适当地调整它。

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

Playground