How to handle optional fields with serde

Handle optional fields in serde by using the #[serde(default)] attribute to assign default values for missing data.

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

use serde::{Deserialize, Serialize};

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

When deserializing, if port is absent, it defaults to 0 (the Default implementation for u16). For custom defaults, implement Default for the type or use #[serde(default = "my_default_func")].