知识卡片
矩形重构保留领域语义
参数应反映领域中的整体。面积函数接收 &Rectangle,表达它只读一个矩形对象,字段名清楚区分长宽。单独的宽高数值或整数对依赖额外的调用约定。若结构体有不变量,可把构造规则集中到它的接口。
相关卡片 [[字段名表达组合语义]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 用结构体组织相关数据 An Example Program Using Structs · 查看原书依据
The area function accesses the width and height fields of the Rectangle instance ❺ (note that accessing fields of a borrowed struct instance does not move the field values, which is why you often see borrows of structs). Our function signature for area now says exactly what we mean: calculate the area of Rectangle, using its width and height fields.
参考来源
- 位置:《The Rust Programming Language(第2版)》第05章 用结构体组织相关数据(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c05.xhtml`,块 0085)
- 结论依据:书中借助命名字段消除矩形元组中宽高位置含义的外部约定。
- 原始内容:The area function accesses the width and height fields of the Rectangle instance ❺ (note that accessing fields of a borrowed struct instance does not move the field values, which is why you often see borrows of structs). Our function signature for area now says exactly what we mean: calculate the area of Rectangle, using its width and height fields.