Enum Defaults With The #[default] Variant

Mark one enum variant with #[default] so derive(Default) selects it, and Settings::default() starts in a sane state.

RustConfig Management

Code

rustsnippet
31 lines
#[derive(Default, Debug, PartialEq)]
enum CacheMode {
    #[default]
    Balanced,
    Aggressive,
    Off,
}

#[derive(Default, Debug)]
struct CacheSettings {
    mode: CacheMode,
    max_entries: usize,
}

fn main() {
    let settings = CacheSettings::default();
    // #[default] 标出的变体成为枚举的默认值
    assert_eq!(settings.mode, CacheMode::Balanced);
    assert_eq!(settings.max_entries, 0);
    println!("default mode: {:?}", settings.mode);

    let custom = CacheSettings { mode: CacheMode::Aggressive, max_entries: 512 };
    println!("custom: {:?}", custom);

    // 与 match 配合:分支覆盖所有变体
    match custom.mode {
        CacheMode::Balanced => println!("balancing memory and hits"),
        CacheMode::Aggressive => println!("keeping up to {} entries", custom.max_entries),
        CacheMode::Off => println!("cache disabled"),
    }
}

How it works

Structurally, expect the function main and nothing else.

A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Caveats

  • No package installation, no environment variables, no setup steps.

Using it

The primary signature is fn main()

The run emits 3 lines — default mode: Balanced, custom: CacheSettings { mode: Aggressive, max_entries: 512 } and keeping up to 512 entries; the balancing memory and hits and cache disabled arms never print for this data.

Key statements

match custom.mode {
CacheMode::Balanced => println!("balancing memory and hits"),
CacheMode::Aggressive => println!("keeping up to {} entries", custom.max_entries),
CacheMode::Off => println!("cache disabled"),
}

Interactive Tools for This Topic

FAQ

What does Enum Defaults With The #[default] Variant print when run?
Running the file directly is enough — expect labeled output lines such as `default mode:`, `custom:`, `balancing memory and hits`.