Nested structures in Rust
Structs inside vectors inside structs — serde follows the whole tree.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Tour {
slug: String,
sections: Vec<Section>,
}
#[derive(Debug, Serialize, Deserialize)]
struct Section {
title: String,
steps: Vec<String>,
}
fn main() -> Result<(), serde_json::Error> {
let tour = Tour {
slug: "traits".to_string(),
sections: vec![Section {
title: "Trait objects".to_string(),
steps: vec!["rs_trait_objects.rs".to_string()],
}],
};
println!("{}", serde_json::to_string_pretty(&tour)?);
Ok(())
}
How it works
- Any field whose type derives the traits just works.
Vec<T>becomes a JSON array of objects.to_string_prettyis the readable form.
Keywords and builtins used here
OkResultSectionStringTourVecfnletmainstructusevec
The run, in numbers
- Lines
- 25
- Characters to type
- 499
- Tokens
- 134
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 77 seconds.
Step 1 of 2 in Shapes, step 7 of 11 in Serde & JSON.