![](/img/trans.png)
[英]Why can a function on a trait object not be called when bounded with `Self: Sized`?
[英]"this trait cannot be made into an object because it requires `Self: Sized`", except it has Sized
这是错误消息:
error[E0038]: the trait `room::RoomInterface` cannot be made into an object
--> src\permanent\registry\mod.rs:12:33
|
12 | pub fn load(id : String) -> Result<Box<dyn RoomInterface>, String>{
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `room::RoomInterface` cannot be made into an object
|
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
--> src\permanent\rooms\mod.rs:36:31
|
36 | pub trait RoomInterface : Copy + Sized {
| ------------- ^^^^ ^^^^^ ...because it requires `Self: Sized`
| | |
| | ...because it requires `Self: Sized`
| this trait cannot be made into an object...
For more information about this error, try `rustc --explain E0038`.
它说要将特征用作 object,它需要 Sized。 除了 Sized 就在那里,在特性的声明中。 它从字面上指向“Sized”这个词并告诉我我需要“Sized”? 这是怎么回事?
问题与您的想法相反:问题是您需要Self: Sized
但只有不需要Self: Sized
的特征才能制成 object。 正如错误消息所述,您必须删除RoomInterface
的Copy
和Sized
的两个边界:
pub trait RoomInterface {
错误消息中链接的文章是一个很好的资源,我建议阅读它: https://doc.rust-lang.org/reference/items/traits.html#object-safety
这个讨论也可能很有趣: https://users.rust-lang.org/t/trait-objects-and-the-sized-trait/14410/2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.