[英]Trait can't be made Object Safe when Hash + PartialEq are Supertraits
I'm pretty new to Rust, so there is the possibility that this will be an easy Question.我是 Rust 的新手,所以这可能是一个简单的问题。
I'm trying to create a small registry for Handlers that should return any struct that implements the TransferObject
Trait:我正在尝试为 Handlers 创建一个小型注册表,它应该返回任何实现TransferObject
Trait 的结构:
pub trait TransferObject: Hash + PartialEq {}
Since I store the Handlers that are registered in a HashMap
the Trait needs the Hash
and PartialEq
as the Supertraits:由于我存储了在HashMap
中注册的处理程序,因此 Trait 需要Hash
和PartialEq
作为 Supertraits:
pub struct RequestHandlerRegistry {
handlers: HashMap<RequestMethod, HashMap<String, RequestHandler<dyn TransferObject>>>,
}
But in the Struct I get the Error, that TransferObject
can't be made into an Object since PartialEq
uses the parameter Self
.但是在 Struct 中我得到了错误,因为PartialEq
使用参数Self
,所以TransferObject
不能变成 Object 。 I already tried to do something like this:我已经尝试过这样做:
pub struct RequestHandlerRegistry {
handlers: HashMap<RequestMethod, HashMap<String, RequestHandler<Box<dyn TransferObject>>>>,
}
But I still get the same Error.但我仍然得到同样的错误。
Is there some way to get around this?有办法解决这个问题吗?
I also created a Playground for easy recreation of the Error.我还创建了一个Playground以便轻松重现错误。
This doesn't work because PartialEq
by default means PartialEq<Self>
.这不起作用,因为默认情况下PartialEq
意味着PartialEq<Self>
。 When using dynamic dispatch ( dyn
) there isn't enough information to know what Self
is and therefore what type of reference the methods of PartialEq
can accept.使用动态调度 ( dyn
) 时,没有足够的信息来了解什么是Self
以及PartialEq
的方法可以接受什么类型的引用。
However, your question belies a misunderstanding that got you into this mess:但是,您的问题掩盖了使您陷入困境的误解:
Since I store the Handlers that are registered in a
HashMap
the Trait needs theHash
andPartialEq
as the Supertraits由于我存储在HashMap
中注册的处理程序,因此 Trait 需要Hash
和PartialEq
作为 Supertraits
This is only true for things you use as keys .这仅适用于您用作键的东西。 There are no such restrictions on values .对值没有这样的限制。
You can therefore drop the supertraits Hash
and PartialEq
from this trait;因此,您可以从此特征中删除超级特征Hash
和PartialEq
; instead you need to add Hash
, PartialEq
, and Eq
to the #[derive]
macro for RequestMethod
, since that's what you're using as a key.相反,您需要将Hash
、 PartialEq
和Eq
添加到RequestMethod
的#[derive]
宏中,因为这就是您用作密钥的内容。
Finally, you will indeed need Box
to hold the dyn TransferObject
values to give them a known size.最后,您确实需要Box
来保存dyn TransferObject
值以给它们一个已知的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.