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.
Code
#[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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.