20.9 Serializing Trait Objects

A common OOP pattern involves storing collections of polymorphic objects on disk. In Rust, you cannot directly serialize trait objects because they contain metadata (such as pointers to vtables) that are meaningful only at runtime. Simply put, a Box<dyn SomeTrait> is not trivially serializable.

If you need to save heterogeneous collections of objects, you have several options:

  1. Use Enums: For a closed set of known types, you can define an enum and implement Serialize/Deserialize via libraries like Serde.
  2. Manual Downcasting: Convert your trait objects to concrete types before serializing. This approach can be complex, as it often relies on carefully managing which types are known at compile time.
  3. Trait Bounds for Serialization: If all your concrete types implement Serialize and Deserialize, you can store them in a container that knows about their concrete types, avoiding the polymorphic trait object problem.

However, there is no direct, automatic serialization of trait objects in Rust.