20.9 Serializing Trait Objects

A common OOP pattern involves storing polymorphic objects on disk. In Rust, you cannot directly serialize trait objects (e.g., Box<dyn SomeTrait>) because they contain runtime-only information (vtable pointers). Some approaches to this problem:

  1. Use Enums: For a fixed set of possible types, define an enum and derive or implement Serialize/Deserialize (e.g., via Serde).
  2. Manual Downcasting: Convert your trait object into a concrete type before serialization. This can be tricky, especially if multiple unknown types exist.
  3. Trait Bounds for Serialization: If every concrete type implements serialization, store them in a container that knows the concrete types, rather than a trait object.

There is no built-in mechanism for automatically serializing a Box<dyn Trait>.