I want to generate 2 types of JSON files
I read that as "2 types of JSON files", so I refer to this as a solution. I would create cover types that are customizable for each context. They can refer to the original type to avoid too much memory overhead:
#[derive(Serialize)] struct LightweightPost<'a> { title: &'a String, } impl<'a> From<&'a Post> for LightweightPost<'a> { fn from(other: &'a Post) -> Self { LightweightPost { title: &other.title, } } } fn main() { let posts = vec![ Post { title: "title".into(), comments: vec![Comment { body: "comment".into() }], }, ]; let listing: Vec<_> = posts.iter().map(LightweightPost::from).collect(); println!("{}", serde_json::to_string(&listing).unwrap()); // [{"title":"title"}] println!("{}", serde_json::to_string(&posts[0]).unwrap()); // {"title":"title","comments":[{"body":"comment"}]} }
playground
In an editorial, I found that this type of multi-type structure is very useful when writing web applications in Ruby using a roaring stone . These new types allow behavioral hangouts specific to specific contexts, such as validation or persistence.
Shepmaster
source share