“这个特征不能被制作成一个对象,因为它需要 `Self: Sized`”,除非它有 Sized

use*_*762 6 rust

这是错误消息:

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`.
Run Code Online (Sandbox Code Playgroud)

它说要将特征用作对象,它需要 Sized。除了 Sized 就在那里,在特征的声明中!它实际上指向“Sized”这个词,并告诉我我需要“Sized”。这是怎么回事?

小智 7

问题与您的想法相反:问题是您需要但只有不需要Self: Sized特征可以制作成对象。正如错误消息所述,您必须删除 for和for 的边界:Self: SizedCopySizedRoomInterface

pub trait RoomInterface {
Run Code Online (Sandbox Code Playgroud)

错误消息中链接的文章是一个很好的资源,我建议阅读它: 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