rust - 如何对具有泛型类型参数的特征进行装箱?

标签 rust

我通常能够使用特征作为 Box<> 之类的类型参数:

trait CtxVal {}
type CtxNodes = HashMap<String, Box<CtxVal>>;

但是当特征有它自己的泛型类型参数时,比如PartialEq ,我被困住了。

type CtxNodes = HashMap<String, Box<PartialEq>>;

我收到错误:

main.rs:6:37: 6:46 error: the type parameter `Rhs` must be explicitly specified in an 
      object type because its default value `Self` references the type `Self`                             
main.rs:6 type CtxNodes = HashMap<String, Box<PartialEq>>;                                                                                                                                
                                              ^~~~~~~~~ 

如果我要提供 PartialEq 的类型,那会是什么?

Box<PartialEq<???>>

最佳答案

您需要指定您希望对象能够比较的内容等于:

fn foo(value: Box<PartialEq<u8>>) -> bool {
    *value == 42
}

fn bar(value: Box<PartialEq<&str>>) -> bool {
    *value == "the answer"
}

关于rust - 如何对具有泛型类型参数的特征进行装箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29947744/

相关文章:

rust - 我应该为可迭代表达式使用什么返回类型?

rust - 这两种为 Rust channel 克隆发送者的方式有什么区别?

rust - 在使用Serde进行序列化时,是否有一种方法可以将结构的字段分组,例如 “flatten”属性的逆函数?

rust - 在类型不匹配的情况下从 for 循环返回修改后的数组

reference - 如何使用 Arc 和 Weak 创建循环引用?

rust - 为什么AtomicUsize的fetch_max返回的值大于其参数?

closures - 如何将变量移出闭包?

rust-如何将这个宏与循环/递归结合起来?

rust - 为什么双重反转迭代器的行为就好像它从未被反转过一样?

rust - 如何指定自定义 Cargo 输出目录?