Default Derives Zero Value Initializers

derive(Default) builds zero-value initializers from field types, and struct update syntax overrides only the fields a caller actually needs.

RustConfig Management

Code

rustsnippet
27 lines
#[derive(Debug, Default)]
struct RetryPolicy {
    max_attempts: u32,
    base_delay_ms: u64,
    timeout_ms: u64,
    // 数值与 bool 类型都有自然的零值默认
    jitter: bool,
}

fn main() {
    // Default::default() 给出全默认值:每个字段取自己类型的零值
    let policy = RetryPolicy::default();
    println!("{policy:?}");

    // 结构体更新语法:在默认值基础上只覆盖需要改的字段
    let tuned = RetryPolicy {
        max_attempts: 5,
        base_delay_ms: 200,
        ..RetryPolicy::default()
    };
    println!("{tuned:?}");

    // 与 unwrap_or_default 配合:缺席配置自动落到默认
    let missing: Option<RetryPolicy> = None;
    let resolved = missing.unwrap_or_default();
    println!("resolved timeout: {}", resolved.timeout_ms);
}

What the code does

Default Derives Zero Value Initializers is built around the function main.

Applying it

Running the file prints labeled results such as resolved timeout: — each operation’s effect is visible in the output.

Statements that matter

let resolved = missing.unwrap_or_default();
let missing: Option<RetryPolicy> = None;

Interactive Tools for This Topic

FAQ

What does Default Derives Zero Value Initializers print when run?
The script runs standalone; its 1 labeled outputs include `resolved timeout:`.