簡體   English   中英

在Rust中,如何修復錯誤“特性`core :: types :: Sized`沒有為`Object +'a`類型實現”

[英]In Rust, how can I fix the error “the trait `core::kinds::Sized` is not implemented for the type `Object+'a`”

使用下面的代碼,我得到一個“特性core::kinds::Sized沒有實現類型Object+'a ”錯誤。 我已經刪除了不需要觸發錯誤的所有其他代碼。

fn main() {
}

pub trait Object {
    fn select(&mut self);
}

pub struct Ball<'a>;

impl<'a> Object for Ball<'a> {
    fn select(&mut self) {
        // Do something
    }
}

pub struct Foo<'a> {
    foo: Vec<Object + 'a>,
}

圍欄: http//is.gd/tjDxWl

完整的錯誤是:

<anon>:15:1: 17:2 error: the trait `core::kinds::Sized` is not implemented for the type `Object+'a`
<anon>:15 pub struct Foo<'a> {
<anon>:16     foo: Vec<Object + 'a>,
<anon>:17 }
<anon>:15:1: 17:2 note: the trait `core::kinds::Sized` must be implemented because it is required by `collections::vec::Vec`
<anon>:15 pub struct Foo<'a> {
<anon>:16     foo: Vec<Object + 'a>,
<anon>:17 }
error: aborting due to previous error
playpen: application terminated with error code 101

我對Rust很新,不知道從哪里開始。 有什么建議?

這里的根本問題是:

您想要存儲對象矢量。 現在,向量是一個平面數組:每個條目都是一個接一個。 但是Object是一個特性,雖然你只為Ball實現了它,你也可以為帽子和三角形實現它。 但那些在內存中的大小可能不同! 因此,對象本身沒有大小。

有兩種方法可以解決這個問題:

  • 使Foo成為通用的,並且只在每個Foo中存儲一種類型的Object。 我覺得這可能不是你想要的。 嬰兒圍欄: http//is.gd/Y0fatg
  • 間接:不是直接將對象存儲在數組中,而是存儲Box。 這是一個圍欄鏈接。 http://is.gd/ORkDRC

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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