← 返回刚才阅读的位置

知识卡片

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

继承的两类需求

理解等级:高级

类继承既可能为了复用已有实现,也可能为了让不同类型可替换。Rust 的 trait 默认方法可复用一段行为,具体实现可覆盖它。有界泛型让所有满足 trait 约束的类型复用调用代码,特征对象还可在运行时处理多种实现。把这两种需求分别处理,可以让类型只承诺适合自身的行为。

相关卡片 [[特征对象统一异构组件]]、[[静态与动态分派]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 面向对象编程特性 Characteristics of Object-Oriented Languages · 查看原书依据

      You would choose inheritance for two main reasons. One is for reuse of code: you can implement particular behavior for one type, and inheritance enables you to reuse that implementation for a different type. You can do this in a limited way in Rust code using default trait method implementations, which you saw in Listing 10-14 when we added a default implementation of the summarize method on the Summary trait.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第17章 面向对象编程特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c17.xhtml`,块 0028) - 结论依据:原文将代码复用单独列为继承动机并用 Summary 举例,邻段再区分类型替换目的。 - 原始内容:You would choose inheritance for two main reasons. One is for reuse of code: you can implement particular behavior for one type, and inheritance enables you to reuse that implementation for a different type. You can do this in a limited way in Rust code using default trait method implementations, which you saw in Listing 10-14 when we added a default implementation of the summarize method on the Summary trait.