簡體   English   中英

“這個特征不能變成 object 因為它需要‘Self: Sized’”,除非它有 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。 正如錯誤消息所述,您必須刪除RoomInterfaceCopySized的兩個邊界:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM