typestar

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

  1. Serialize writes the struct out, Deserialize reads it in.
  2. to_string and from_str are the serde_json entry points.
  3. Field names become JSON keys unless you rename them.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Deriving, step 1 of 11 in Serde & JSON.

Next →