4
使用下面的代碼,我得到了「特性core::kinds::Sized
沒有爲類型Object+'a
「執行錯誤。我已經刪除了不需要觸發錯誤的所有其他代碼。在Rust中,我該如何解決錯誤「特性`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>,
}
完整的錯誤是:
<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
我很新生鏽,真的不知道從哪裏何去何從。有什麼建議麼?
請注意第三個解決方案:使用'enum'而不是特徵。這關閉了可以表示的一組類型,因此假設所有的都是'Sized',它會創建一個'Sized''enum'。 –
我正在適應從使用enum方法的另一代碼選擇。它運行良好,但對我來說不夠靈活。每次添加一個實現Object方法的新東西時,我都必須在代碼中查找並更改10-15個位置。在更簡單的代碼中,這可以正常工作,但我的更改已經開始超出它。 – ben
感謝您的回答。您提供的圍欄鏈接都沒有編譯 - 僅供參考,因爲包含圍欄的答案非常適合! –