Search CTRL + K

Dyn Compatibility

只有动态兼容(dyn compatibility)的 trait 才能作为 trait 对象 的基础 trait。动态兼容 trait 的条件有:

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> where P is one of the types above
      • Not have an opaque return type; that is,
        • Not be an async fn (which has a hidden Future type).
        • Not have a return position impl Trait type (fn example(&self) -> impl Trait).
      • Not have a where Self: Sized bound (receiver type of Self (i.e. self) implies this).
    • Explicitly non-dispatchable functions require:
      • Have a where Self: Sized bound (receiver type of Self (i.e. self) implies this).

  1. https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility ↩︎