This has been implemented by dtolnay.
The concept is quite clever ans is explained in the README
:
How does it work?
We use the
inventory
crate to produce a registry of impls of your trait, which is built on thector
crate to hook up initialization functions that insert into the registry. The firstBox<dyn Trait>
deserialization will perform the work of iterating the registry and building a map of tags to deserialization functions. Subsequent deserializations find the right deserialization function in that map. Theerased-serde
crate is also involved, to do this all in a way that does not break object safety.
To summarize, every implementation of the trait declared as [de]serializable is registered at compile-time, and this is resolved at runtime in case of [de]serialization of a trait object.