typestar

Optional and defaulted fields in Rust

Missing keys, null values and fields you would rather not emit at all.

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Settings {
    theme: String,
    #[serde(default)]
    editor_mode: bool,
    #[serde(default = "default_limit")]
    time_limit: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    note: Option<String>,
}

fn default_limit() -> u32 {
    60
}

fn main() -> Result<(), serde_json::Error> {
    let s: Settings = serde_json::from_str(r#"{"theme":"monokai"}"#)?;
    println!("{:?}", s);
    println!("{}", serde_json::to_string(&s)?);
    Ok(())
}

How it works

  1. Option<T> accepts a missing key or a null.
  2. #[serde(default)] fills in the type's default instead.
  3. skip_serializing_if keeps empty values out of the output.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
496
Tokens
121
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 69 seconds.

Type this snippet

Step 2 of 3 in Field attributes, step 5 of 11 in Serde & JSON.

← Previous Next →