知识卡片
布尔包装区分参数角色
DoubleSided(bool)与ColorOutput(bool)把两个布尔参数变成独立类型,使调用点说明选项角色,也能阻止调换顺序。若未来状态可能超过两种,枚举更易扩展;包装布尔主要适合确实二元且需要区分身份的选项。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 1. Types Item 6: Embrace the newtype pattern · 查看原书依据
DoubleSided(pub bool); struct ColorOutput(pub bool); fn print_page(sides: DoubleSided, color: ColorOutput) { // ... } print_page(DoubleSided(true), ColorOutput(false)); If size efficiency or binary compatibility is a concern, then the #[repr(transparent)] attribute ensures that a newtype has the same representation in memory as the inner type. That’s the sim
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Item 6: Embrace the newtype pattern》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u035-ch01-046)。
- 结论依据:原文在“DoubleSided”附近的定义、例子或代码支撑本卡核心说明:DoubleSided(bool)与ColorOutput(bool)把两个布尔参数变成独立类型,使调用点说明选项角色,也能阻止调换顺序。边界按已读前提解释;示例未执行。
- 原始内容:DoubleSided(pub bool); struct ColorOutput(pub bool); fn print_page(sides: DoubleSided, color: ColorOutput) { // ... } print_page(DoubleSided(true), ColorOutput(false)); If size efficiency or binary compatibility is a concern, then the #[repr(transparent)] attribute ensures that a newtype has the same representation in memory as the inner type. That’s the sim