1

I want to have a JSON config file of the form:

{
    "general_option_foo": true, 
    "general_option_bar": "hello world!", 
    "modules": [
        { "name": "moduleA", "module_options" : {"optFoo":"foo"} }, 
        { "name" : "moduleB", "module_options" : {"optBar":[3,4], "optBuzz": true} }
        { "name": "moduleA", "module_options" : {"optFoo":"bar"} }, 
    ]
}

My application supports many different modules that are each configurable, and which get instantiated how many times and with what options should be determined by the config file.

With serde, everything will work fine if I make one giant struct that contains everything, but I want a more modular design. The creator of each module should be able to define a serializable struct for their module's parameters without having to look at the others. In particular, I am looking to avoid having one big central enum with all modules, I want to use trait based polymorphism instead.

How do I deserialize into trait, not a concrete type? is similar, but all the answers fall back to using a central enum.

I believe what I want is something like:

#[derive(Deserialize)]
struct ModuleConfig {
    name: String,
    module_options: Box<dyn Deserialize>,
}

#[derive(Deserialize)]
struct GeneralOptions {
    general_option_foo: bool,
    general_option_bar: String,
    modules: Vec<ModuleConfig>,
}

I assume serde is going to need some help with using the module name to look up the corresponding trait impl to actually do the deserialization. Is this possible? Is there a good example somewhere I could work from?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Joseph Garvin
  • 20,727
  • 18
  • 94
  • 165
  • 1
    It looks like your question might be answered by the answers of [How do I deserialize into trait, not a concrete type?](https://stackoverflow.com/q/42392935/155423) or [How can deserialization of polymorphic trait objects be added in Rust if at all?](https://stackoverflow.com/q/44231020/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Aug 04 '20 at 19:03
  • @Shepmaster done – Joseph Garvin Aug 04 '20 at 19:07
  • *but all the answers fall back to using a central enum* — they [literally don't](https://stackoverflow.com/a/57818325/155423). – Shepmaster Aug 04 '20 at 19:08
  • I've also added [another answer](https://stackoverflow.com/a/63253738/155423) that has a complete example. – Shepmaster Aug 04 '20 at 19:21
  • @Shepmaster sorry I only saw your first link (did you edit your comment?) – Joseph Garvin Aug 04 '20 at 19:22
  • Yes, that's what the pencil icon next to the comment indicates. Comments are refreshed when you submit your own comment to help show that. – Shepmaster Aug 04 '20 at 19:23
  • 1
    @Shepmaster thanks, your complete example is perfect! – Joseph Garvin Aug 04 '20 at 20:15

0 Answers0