知识卡片

普通读书笔记卡 · 743.d.2.b.1.a.2

新类型不会继承内部实现

理解等级:中级

newtype虽然包含内部值,却不会自动继承内部类型的trait实现。适合派生的Debug、Clone等可在字段满足条件时derive,其余如Display可能需要转发到self.0。增加包装时要明确暴露哪些能力,不能为了恢复一切便利而无条件打开全部内部操作。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 1. Types Newtype Limitations · 查看原书依据

      Newtype Limitations The newtype pattern solves these two classes of problems—preventing unit conversions and bypassing the orphan rule—but it does come with some awkwardness: every operation that involves the newtype needs to forward to the inner type. On a trivial level, that means that the code has to use thing.0 throughout, rather than just thing, but tha

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Newtype Limitations》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u037-ch01-048)。 - 结论依据:原文在“Newtype Limitations”附近的定义、例子或代码支撑本卡核心说明:newtype虽然包含内部值,却不会自动继承内部类型的trait实现。边界按已读前提解释;示例未执行。 - 原始内容:Newtype Limitations The newtype pattern solves these two classes of problems—preventing unit conversions and bypassing the orphan rule—but it does come with some awkwardness: every operation that involves the newtype needs to forward to the inner type. On a trivial level, that means that the code has to use thing.0 throughout, rather than just thing, but tha