Maps and round trips in Rust
Serializing a map, then reading it back into the same type.
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Progress {
tours: BTreeMap<String, u32>,
}
fn main() -> Result<(), serde_json::Error> {
let mut tours = BTreeMap::new();
tours.insert("traits".to_string(), 15);
tours.insert("basics".to_string(), 39);
let before = Progress { tours };
let json = serde_json::to_string(&before)?;
println!("{json}");
let after: Progress = serde_json::from_str(&json)?;
println!("equal: {}", before == after);
Ok(())
}
How it works
- A
HashMapbecomes a JSON object; keys must be strings. BTreeMapkeeps the keys sorted in the output.- A round trip is the cheapest test of a model.
Keywords and builtins used here
BTreeMapOkProgressResultStringfnletmainmutstructu32use
The run, in numbers
- Lines
- 21
- Characters to type
- 530
- Tokens
- 147
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 88 seconds.
Step 3 of 3 in Deriving, step 3 of 11 in Serde & JSON.