← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 6074.c.13 · 生成模型:未记录

受控构造集中校验

理解等级:高级

将 1 到 100 的约束写入 Guess 类型:入口先验证再构造,字段私有确保外部不能构造或改成非法值,只读 getter 提供需要的原值。其他函数只接收 Guess 就能省去重复检查。外部数据可能越界时,在边界保留返回错误或提示重试的路径。

相关卡片 [[公开类型有不同粒度]]、[[按可恢复性选择失败方式]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 错误处理 Creating Custom Types for Validation · 查看原书依据

      Next, we implement a method named value that borrows self, doesn’t have any other parameters, and returns an i32 ❻. This kind of method is sometimes called a getter because its purpose is to get some data from its fields and return it. This public method is necessary because the value field of the Guess struct is private.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第09章 错误处理(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c09.xhtml`,块 0168) - 结论依据:原文说明私有字段把外部使用者限制到验证构造器,并用 getter 保留读取能力。 - 原始内容:Next, we implement a method named value that borrows self, doesn’t have any other parameters, and returns an i32 ❻. This kind of method is sometimes called a getter because its purpose is to get some data from its fields and return it. This public method is necessary because the value field of the Guess struct is private.