![](/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.