如何装箱具有泛型类型参数的特征?
How to box a trait that has generic type parameters?
我通常能够使用特征作为 Box<> 之类的类型参数:
trait CtxVal {}
type CtxNodes = HashMap<String, Box<CtxVal>>;
但是当 trait 有它自己的通用类型参数时,比如 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"
}
我通常能够使用特征作为 Box<> 之类的类型参数:
trait CtxVal {}
type CtxNodes = HashMap<String, Box<CtxVal>>;
但是当 trait 有它自己的通用类型参数时,比如 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"
}