Search code examples
rustserdetoml

How to deserialize two different structures and file formats using toml-rs and serde_derive?


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?


Solution

  • 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.