实现说明
用 #[default] 指定枚举默认变体可以归结为函数 main。
match 把每种情况写明白;漏写一个就编译不过。
使用要点
- 直接运行文件,输出会带上标签,比如
default mode:、custom:、balancing memory and hits——输出的每一行都能指回产生它的那次调用。
常见问题
运行「用 #[default] 指定枚举默认变体」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 default mode:、custom:、balancing memory and hits 标签标明各步骤。
核心语句
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"),
}
代码示例
#[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"),
}
}