title: How can deserialization of polymorphic trait objects be added in Rust if at all?
body: <p>I'm trying to solve the problem of serializing and deserializing <code>Box&lt;SomeTrait&gt;</code>. I know that in the case of a closed type hierarchy, the recommended way is to use an enum and there are no issues with their serialization, but in my case using enums is an inappropriate solution.</p>
  
  <p>At first I tried to use Serde as it is the de-facto Rust serialization mechanism. Serde is capable of serializing <code>Box&lt;X&gt;</code> but not in the case when <code>X</code> is a trait. The <a href="https://docs.serde.rs/serde/trait.Serialize.html" rel="noreferrer"><code>Serialize</code></a> trait can’t be implemented for trait objects because it has generic methods. This particular issue can be solved by using <a href="https://github.com/dtolnay/erased-serde" rel="noreferrer">erased-serde</a> so serialization of <code>Box&lt;SomeTrait&gt;</code> can work.</p>
  
  <p>The main problem is deserialization. To deserialize polymorphic type you need to have some type marker in serialized data. This marker should be deserialized first and after that used to dynamically get the function that will return <code>Box&lt;SomeTrait&gt;</code>.</p>
  
  <p><code>std::any::TypeId</code> could be used as a marker type, but the main problem is how to dynamically get the deserialization function. I do not consider the option of registering a function for each polymorphic type that should be called manually during application initialization.</p>
  
  <p>I know two possible ways to do it:</p>
  
  <ol>
  <li>Languages that have runtime reflection like C# can use it to get
  deserialization method. </li>
  <li>In C++, the cereal library uses magic of static objects to register deserializer in a static map at the library initialization time.</li>
  </ol>
  
  <p>But neither of these options is available in Rust. How can deserialization of polymorphic objects be added in Rust if at all? </p>