实现具有关联特征类型的特征

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() {}

Play link

这里的目的是使用关联类型来使 FooStore 特征不需要 impl<F:Fooer, T: FooStore<F>> FooStore<F> for DB 的笨拙和有问题的语法,因为它经常抱怨 F 没有被使用。

但是,此功能上的 official docs 显示实现底层关联类型的对象 - 但不是特征。在这个例子中,DB不知道什么结构可能被传递给store_foo(..),所以它需要使用一个特征来解决这个问题。

话虽如此,我怎样才能让关联类型在 impl 期间使用特征?也就是我怎么写type T = Fooer;?还是我用错了?

注意:我在构建这个例子时遇到了一些问题,我正在尝试更正它。我遇到的错误是:

cargo: the trait `Fooer` cannot be made into an object [E0038]

The intent here is to use associated types to make the FooStore trait not require the awkward and problematic syntax of impl<F:Fooer, T: FooStore<F>> FooStore<F> for DB because that often complains about F not being used.

您的结构 DB 需要将实现 Fooer 的具体类型分配给 FooStore::TFooer 是一个特征,但也可以用作未调整大小的类型。但是,您不能在此处使用未确定大小的类型,因为您不能按值传递未确定大小类型的参数(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>在概念上拥有类型[=23=的对象].