Deriving Serialize and Deserialize in Rust
Two derives and a struct becomes JSON in both directions.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Run {
lang: String,
tpm: u32,
accuracy: f64,
}
fn main() -> Result<(), serde_json::Error> {
let run = Run { lang: "rust".to_string(), tpm: 104, accuracy: 97.5 };
let json = serde_json::to_string(&run)?;
println!("{json}");
let parsed: Run = serde_json::from_str(&json)?;
println!("{:?}", parsed);
Ok(())
}
How it works
Serializewrites the struct out,Deserializereads it in.to_stringandfrom_strare the serde_json entry points.- Field names become JSON keys unless you rename them.
Keywords and builtins used here
OkResultRunStringf64fnletmainstructu32use
The run, in numbers
- Lines
- 18
- Characters to type
- 393
- Tokens
- 116
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 70 seconds.
Step 1 of 3 in Deriving, step 1 of 11 in Serde & JSON.