I'm creating a Tumblr API wrapper. Unfortunately the way it's designed does not really mesh with Rust's data representation.
Serde has introduced the awesome tag
decorator which makes sorting enums very easy when it is internally tagged.
However, Tumblr's types only differ by a few fields. For instance, all posts have the following fields, no matter the type:
id,
url,
timestamp,
date,
format,
... etc
However, depending on the post type, they may also contain other data. Photo types contain "photo_url", while text types include "title". Due to this, I can write my data models like this:
pub enum TextPost {
id: usize,
... all other generic fields ...
title: String,
}
pub enum PhotoPost {
id: usize,
... all other generic fields ...
photo_url: String,
}
However, that would lead to a lot of duplication! I was wondering if there is a way to consolidate that information on to another structure. For example, take the models.rs
file above.
I want to store all the generic fields in a struct with the field info
. However, since the JSON does not put all generic fields in any
structure, I cannot use this approach. Is there a way I can have minimal duplication while still obtaining all the generic info? Is there
a serde decorator I can apply to the "info" field that tells it "hey, I want all the fields on this exposed on a root level when deserializing!"
Thank you!