0

I am using toml-rs and serde_derive to deserialize TOML files my app uses to describe data structures.

I have everything working with my first data structure which corresponds to one TOML file definition with obligatory and optional fields.

Now I want to use it to deserialize another data structure that is described in another TOML file, with different fields.

How do I specify to the deserializer (I am using toml::from_str(&contents)) which structure type I want to deserialize into?

Related question - is it possible to put the type into the file itself, so that deserialization can be more generic, and the deserializer can detect the type to deserialize from the file itself?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Andrew Mackenzie
  • 5,477
  • 5
  • 48
  • 70
  • 1
    *How do I specify to the deserializer which structure type I want to deserialize into?* — you do it in the **exact same way** you specified what type to deserialize into the first time. Show us how you tried to solve the problem. – Shepmaster Nov 22 '17 at 13:41

1 Answers1

3

toml::from_str deserializes into the type that is expected from the expression. So

let x: Foo = toml::from_str(something)?;

will use the Deserialize impl of Foo.

You can also explicitly specify what type to deserialize into via generic arguments:

let x = toml::from_str::<Foo>(something)?;

Also, related - is it possible to put the type into the file itself, so that deserialization can be more generic, and the deserializer can detect the type to deserialize from the file itself?

You can do that with enums. Each variant can hold a different type. To figure out the exact design I suggest you implement Serialize for an enum, serialize it to your target format and you'll see how to do the runtime type specification. I'm not sure if toml supports enums, but json certainly does.

oli_obk
  • 28,729
  • 6
  • 82
  • 98
  • 1
    That answers the main part of my question, so I have accepted it. I guess the part I'm struggling with most in fact is that I want to deserialize a toml file into one of a number of different struct types - without knowing apriori what format/type is in the file.... If you have any references for the enum idea it would be great. If you prefer I ask a separate question for that, then I can. Thanks – Andrew Mackenzie Nov 22 '17 at 18:02