简体   繁体   中英

"this trait cannot be made into an object because it requires `Self: Sized`", except it has Sized

Here's the error message:

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`.

It says that to use the trait as an object, it requires Sized. Except that Sized is right there, in the declaration of the trait. It literally points to the word "Sized" and tells me I need to have "Sized"? What's going on?

The problem is opposite to what you think: The problem is that you require Self: Sized but only traits which do not require Self: Sized can be made into an object. As the error message states you must remove both bounds for Copy and Sized for RoomInterface :

pub trait RoomInterface {

The article linked in the error message is a great resource, I recommend reading it: https://doc.rust-lang.org/reference/items/traits.html#object-safety

Also this discussion might be interesting: https://users.rust-lang.org/t/trait-objects-and-the-sized-trait/14410/2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM