假设有一个集合特征具有与其项目相关联的类型:

trait CollectionItem {
    // ...
}

trait Collection {
    type Item: CollectionItem;
    
    fn get(&self, index: usize) -> Self::Item;
    // ...
}

我可以通过某种方式将其类型擦除为同时对CollectionCollectionItem特性使用动态调度的类型吗?例如,将其包装成类似以下内容的形式:

struct DynCollection(Box<dyn Collection<Item=Box<dyn CollectionItem>>>);
impl DynCollection {
  fn get(&self, index: usize) -> Box<dyn CollectionItem> {
    // ... what to do here?
  }
}
impl <C: Collection> From<C> for DynCollection {
  fn from(c: C) -> Self {
    // ... what to do here?
  }
}

Playground

推荐答案

您可以添加私有的、类型擦除的辅助对象特征:

trait DynCollectionCore {
    fn get_dyn(&self, index: usize) -> Box<dyn CollectionItem>;
}

impl<C> DynCollectionCore for C
where
    C: ?Sized + Collection,
    C::Item: 'static,
{
    fn get_dyn(&self, index: usize) -> Box<dyn CollectionItem> {
        Box::new(self.get(index))
    }
}

然后使用以下代码构建包装器类型:

struct DynCollection(Box<dyn DynCollectionCore>);

impl DynCollection {
    fn new<C>(inner: C) -> Self
    where
        C: Collection + 'static,
        C::Item: 'static,
    {
        Self(Box::new(inner))
    }
}

impl Collection for DynCollection {
    type Item = Box<dyn CollectionItem>;

    fn get(&self, index: usize) -> Box<dyn CollectionItem> {
        self.0.get_dyn(index)
    }
}

// note: something like this is also needed for `Box<dyn CollectionItem>:
//       CollectionItem` to be satisfied
impl<T: ?Sized + CollectionItem> CollectionItem for Box<T> {
    // ...
}

Rust相关问答推荐

如何初始化match声明中的两个变量而不会激怒borrow 判断器?

什么是谓词的简短和简洁类型

重新导出proc宏导致未解决的extern crate错误""

阻止websocket中断的中断中断的终端(操作系统错误4)

关联类型(类型参数)命名约定

如果A == B,则将Rc A下推到Rc B

Arrow RecordBatch as Polars DataFrame

如何在Bevy/Rapier3D中获得碰撞机的计算质量?

使用Clap时如何将String作为Into Str参数传递?

无法理解铁 rust &S错误处理

在文件链实施中绕过borrow 判断器

Rust面向对象设计模式

有没有一种方法可以创建一个闭包来计算Rust中具有随机系数的n次多项式?

类型生命周期绑定的目的是什么?

`UnsafeCell` 在没有锁定的情况下跨线程共享 - 这可能会导致 UB,对吗?

std mpsc 发送者通道在闭包中使用时关闭

Button.set_hexpand(false) 不会阻止按钮展开

为什么 Rust 字符串没有短字符串优化 (SSO)?

在 Rust 中,将可变引用传递给函数的机制是什么?

如何在 Rust 的泛型函​​数中同时使用非拥有迭代器和消费迭代器?