How can deserialization of polymorphic trait objects be added in Rust if at all?

后端 未结 3 605
余生分开走
余生分开走 2020-12-01 21:05

I\'m trying to solve the problem of serializing and deserializing Box. I know that in the case of a closed type hierarchy, the recommended way

3条回答
  •  一个人的身影
    2020-12-01 21:43

    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 the ctor crate to hook up initialization functions that insert into the registry. The first Box 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. The erased-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.

提交回复
热议问题