【发布时间】:2023-02-23 22:45:30
【问题描述】:
我想创建一个包含特征的变量。编译时特征实现是未知的。因此,我需要一个特征对象。这适用于“正常”特征,但不适用于特征具有关联类型的情况。
为什么?让AssTrait 成为关联类型的特征,AssTraitImpl 成为实现该特征的结构(参见下面的示例)。现在,AssTraitImpl 实例的特征对象可以指向表示为 AssTraitImpl 实现的方法的 vtable。还是我错了?
例子
下面的代码不起作用。然而,如果我们从特征中删除关联类型。
trait AssTrait {
type Item;
}
struct AssTraitImpl {
}
impl AssTrait for AssTraitImpl {
type Item = i32;
}
fn main() {
let var: &dyn AssTrait;
}
我收到此错误消息:
error[E0191]: the value of the associated type `Item` (from trait `AssTrait`) must be specified
--> src/main.rs:20:20
|
9 | type Item;
| --------- `Item` defined here
...
20 | let var : &dyn AssTrait;
| ^^^^^^^^ help: specify the associated type: `AssTrait<Item = Type>`
【问题讨论】:
-
如果您告诉 Rust 关联类型是什么具体类型,它也会起作用(请参阅错误消息)。这也行得通:
let var: &dyn AssTrait<Item = i32>
标签: rust associated-types trait-objects