← 返回起始笔记位置

知识卡片

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

新类型隔离单位与接口

理解等级:中级

用单字段结构体包装既有数据可以得到独立类型。Millimeters 与 Meters 都使用 u32 保存,但期待毫米的函数不能直接接收米,跨单位算术需明确转换。也可使内部字段私有,把存储细节与外部 API 分开,例如通过 People 的公共方法管理内部映射。

相关卡片 [[类型别名复用签名]]、[[本地包装实现外部特征]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 高级特性 Advanced Types · 查看原书依据

      This section assumes you’ve read the earlier section “Using the Newtype Pattern to Implement External Traits” on page 439. The newtype pattern is also useful for tasks beyond those we’ve discussed so far, including statically enforcing that values are never confused and indicating the units of a value.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第19章 高级特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c19.xhtml`,块 0226) - 结论依据:原文说明米和毫米包装同类型却不能互传,下一段扩展到封装实现与 API。 - 原始内容:This section assumes you’ve read the earlier section “Using the Newtype Pattern to Implement External Traits” on page 439. The newtype pattern is also useful for tasks beyond those we’ve discussed so far, including statically enforcing that values are never confused and indicating the units of a value.