[Advanced Rust] 2.6. API Design Principles of Flexibility Pt.2 - Object Safety, API Design, and Generic Trait Methods
2.6.1. Object Safety When defining a trait, whether it is object-safe is also part of the unstated contract. Object safety is a concept in Rust related to trait objects . It determines whether a trait can be dynamically dispatched, that is, whether it can be used in the form of dyn Trait . Traits That Are Object-Safe Must Satisfy the Following Conditions (Based on RFC 255) All supertraits must also be object-safe If a trait inherits from other traits, then those supertraits must also be object-safe. It must not require Sized A trait cannot use Sized as a supertrait, meaning it cannot contain a Self: Sized bound, because the size of a trait object is unknown at compile time. It cannot have associated constants . It cannot have associated types with type parameters . All associated functions (methods) must satisfy one of the following rules : Dispatchable functions : They cannot have any type parameters, though lifetime parameters are allowed. They must be methods, and Self may only appear in receiver positions such as: &self &mut self Box<Self> Rc<Self> Arc<Self> Pin<P> (where P is one of the types above) They cannot require Self: Sized , otherwise the trait would only be usable for types with known size and object safety would be broken. Explicitly non-dispatchable functions : They may return Self , but such functions must require Self: Sized , so they cannot be called on trait objects and can only be used with concrete types. If you cannot remember all of the above, just remember object safety describes whether a trait can be safely turned into a trait object . What Object Safety Does If a trait is object-safe, meaning it satisfies all of the conditions above, then we can use dyn Trait to treat different types that implement the trait as a single generic type. If it is not object-safe, the compiler will prevent you from using dyn Trait . Object Safety and API Design When designing APIs, it is recommended to make traits object-safe, even if that slightly reduces con