![](/img/trans.png)
[英]Problem with implementing a trait over another trait with associated types in Rust
[英]Implementing a trait that has associated trait types
我在學習關聯類型時遇到了麻煩。 我的問題代碼:
trait Fooer {
fn foo(&self);
}
trait FooStore {
type T: Fooer;
fn store_foo(&self, fooer: Self::T);
}
#[allow(dead_code)]
struct DB {}
impl FooStore for DB {
type T = Fooer;
fn store_foo(&self, _fooer: Self::T) {}
}
fn main() {}
這里的目的是使用關聯的類型來使FooStore
特性不要求impl<F:Fooer, T: FooStore<F>> FooStore<F> for DB
的笨拙和有問題的語法,因為它常常抱怨未使用F
但是,有關此功能的官方文檔顯示了實現底層關聯類型的對象-但沒有特征。 在此示例中, DB
不知道哪些結構可能傳遞給store_foo(..)
,因此它需要使用特征來解決此問題。
話雖如此,如何在impl
期間獲取關聯類型以使用trait? 也就是說,我該如何寫type T = Fooer;
? 還是我以某種方式使用了這個錯誤?
注意 :我在構造此示例時遇到了一些麻煩,現在嘗試糾正此問題。 我遇到的錯誤是:
cargo: the trait `Fooer` cannot be made into an object [E0038]
這里的目的是使用關聯的類型來使
FooStore
特性不要求impl<F:Fooer, T: FooStore<F>> FooStore<F> for DB
的笨拙和有問題的語法,因為它常常抱怨未使用F
您的結構DB
需要為FooStore::T
分配實現Fooer
的具體類型。 Fooer
是一個特征,但也可以用作未定型類型。 但是,您不能在此處使用未調整大小的類型,因為您無法通過值傳遞未調整大小類型的參數( FooStore::store_foo
要求)。
如果您不希望DB
為FooStore::T
分配特定類型,則可以使DB
通用。
use std::marker::PhantomData;
#[allow(dead_code)]
struct DB<F: Fooer> {
_phantom: PhantomData<F>,
}
impl<F: Fooer> FooStore for DB<F> {
type T = F;
fn store_foo(&self, _fooer: Self::T) {}
}
注意PhantomData
的使用:我們使用它來強制使用參數T
,它還指示DB<T>
從概念上講擁有T
類型的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.