How to Handle Default Values in Serde

Use #[serde(default)] on struct fields to provide fallback values during deserialization when keys are missing.

Use the #[serde(default)] attribute on a struct field to assign a default value when deserializing JSON that omits that field. You must also implement Default for the type or provide a custom default function.

use serde::Deserialize;

#[derive(Deserialize)]
struct Config {
    #[serde(default)]
    timeout: u32,
}

impl Default for Config {
    fn default() -> Self {
        Self { timeout: 30 }
    }
}

Alternatively, use #[serde(default = "my_default")] to call a specific function:

fn my_default() -> u32 { 60 }

#[derive(Deserialize)]
struct Config {
    #[serde(default = "my_default")]
    timeout: u32,
}