知识卡片
枚举区分同形业务选项
把多个含义不同的bool参数改成独立enum,可让调用点说明是在选单双面还是颜色,并让参数调换成为类型错误。枚举适合可能扩展的备选项;永远只有两种状态时也可用newtype表达身份,重点是区分语义而非统一替换所有bool。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 1. Types enums · 查看原书依据
each enum definition creates a distinct type, this can be used to improve readability and maintainability of functions that take bool arguments. Instead of: print_page(/* both_sides= */ true, /* color= */ false); a version that uses a pair of enums: pub enum Sides { Both, Single, } pub enum Output { BlackAndWhite, Color, } pub fn print_page(sides: Sides, col
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《enums》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u010-ch01-006)。
- 结论依据:原文在“each enum definition creates a distinct type”附近的定义、例子或代码支撑本卡核心说明:把多个含义不同的bool参数改成独立enum,可让调用点说明是在选单双面还是颜色,并让参数调换成为类型错误。边界按已读前提解释;示例未执行。
- 原始内容:each enum definition creates a distinct type, this can be used to improve readability and maintainability of functions that take bool arguments. Instead of: print_page(/* both_sides= */ true, /* color= */ false); a version that uses a pair of enums: pub enum Sides { Both, Single, } pub enum Output { BlackAndWhite, Color, } pub fn print_page(sides: Sides, col