gpt4 book ai didi

rust - 断言特征对象的相等性?

转载 作者:行者123 更新时间:2023-12-04 15:02:39 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to test for equality between trait objects?

(3 个回答)


8 个月前关闭。




平常的 assert_eq!宏要求 PartialEq 跨结构实现 - 我有一个特征对象向量,Vec<Box<dyn Element>> ,其中 Element 是需要调试的特征,pub trait Element: std::fmt::Debug .我不能类似地要求 PartialEq因为它需要 Self 作为类型参数,编译器无法将其转换为 trait 对象。
我看到的解决方案涉及在 trait 定义中需要一个 eq 关联函数,这对我没有吸引力,因为这只是调试代码,我认为包含一个无用的方法是没有好处的并且可能会在 cargo test 之外添加到 trait 的 API 中 build 。
有没有其他(可能不安全的)方法来比较两个特征对象?

最佳答案

很可能你应该实现任何你需要的只是为了调试目的。查询 conditional compilation macros .
无论如何,既然你已经知道他们是 Debug绑定(bind),您可以尝试将其用作比较。当然,你需要适本地调整它。

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

关于rust - 断言特征对象的相等性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66701011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com