How to Handle Optional Fields in Serde

Use the #[serde(default)] attribute on struct fields to automatically assign a default value when the field is missing during deserialization.

Use the #[serde(default)] attribute on the struct field to provide a default value when the field is missing in the input.

use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
struct Config {
    name: String,
    #[serde(default)]
    port: u16,
}

This ensures that if port is absent in the JSON, it defaults to 0 (the default for u16). For custom defaults, implement Default for the type or use #[serde(default = "custom_default")].