Dyn Compatibility
只有动态兼容(dyn compatibility)的 trait 才能作为 trait 对象 的基础 trait。动态兼容 trait 的条件有:
- 所有超类 trait 也是动态兼容的。
- 超类 trait 中不能有
Sized
。也就是说不能有Self: Sized
约束。 - 没有任何关联常量。
- 没有任何泛型关联类型。
- 所有关联函数必须可以从 trait 对象 调度分派,或者是显式不可调度分派:
- 可调度分派函数要求:
- 不能有类型参数(尽管生存期参数可以有)。
- 作为方法时,Self 只能出现在方法的接受者(receiver)的类型里,其它地方不能使用 Self:
&Self
(i.e.&self
)&mut Self
(i.e&mut self
)Box<Self>
Rc<Self>
Arc<Self>
Pin<P>
当P
是上面类型中的一种
- 没有
where Self: Sized
约束(即接受者的类型Self
(例如:self
) 不能有Sized
约束)。
- 显式不可调度分派函数要求:
- 有
where Self: Sized
约束(即接受者的类型Self
(例如:self
) 有 Sized约束
)。
- 有
- 可调度分派函数要求:
Dyn compatibility
A dyn-compatible trait can be the base trait of a trait object. A trait is dyn compatible if it has the following qualities:[1]
- All supertraits must also be dyn compatible.
- Sized must not be a supertrait. In other words, it must not require
Self: Sized
. - It must not have any associated constants.
- It must not have any associated types with generics.
- All associated functions must either be dispatchable from a trait object or be explicitly non-dispatchable:
- Dispatchable functions must:
- Not have any type parameters (although lifetime parameters are allowed).
- Be a method that does not use
Self
except in the type of the receiver:&Self
(i.e.&self
)&mut Self
(i.e&mut self
)Box<Self>
Rc<Self>
Arc<Self>
Pin<P>
whereP
is one of the types above
- Not have an opaque return type; that is,
- Not be an
async fn
(which has a hiddenFuture
type). - Not have a return position
impl Trait
type (fn example(&self) -> impl Trait
).
- Not be an
- Not have a
where Self: Sized
bound (receiver type ofSelf
(i.e.self
) implies this).
- Explicitly non-dispatchable functions require:
- Have a
where Self: Sized
bound (receiver type ofSelf
(i.e.self
) implies this).
- Have a
- Dispatchable functions must: