知识卡片

普通读书笔记卡 · 6074.d.1.a.17 · 生成模型:未记录

覆盖式实现复用已有能力

理解等级:中级

覆盖式实现为满足一组条件的类型普遍实现一个 trait。例如所有实现 Display 的适用类型都能获得 ToString,可以直接调用 3.to_string()。这把已有格式化能力转成字符串转换,避免逐个类型重复声明。

相关卡片 [[特征约束决定方法可用性]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 泛型类型、trait 与生命周期 Traits as Parameters · 查看原书依据

      We can also conditionally implement a trait for any type that implements another trait. Implementations of a trait on any type that satisfies the trait bounds are called blanket implementations and are used extensively in the Rust standard library. For example, the standard library implements the ToString trait on any type that implements the Display trait. The impl block in the standard library looks similar to this code:

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第10章 泛型类型、trait 与生命周期(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c10.xhtml`,块 0187) - 结论依据:原文定义 blanket implementation 并用 Display 到 ToString 展示覆盖范围。 - 原始内容:We can also conditionally implement a trait for any type that implements another trait. Implementations of a trait on any type that satisfies the trait bounds are called blanket implementations and are used extensively in the Rust standard library. For example, the standard library implements the ToString trait on any type that implements the Display trait. The impl block in the standard library looks similar to this code: