知识卡片
关联类型属于实现契约
trait 可声明 type Item,方法用 Self::Item 表明输出跟随当前实现。Iterator 在 Counter 上只能有一个对应实现,Item 选定一次,next 不必在每处调用重复选类型。假如把 Item 换成 trait 的泛型参数,Counter 可以对多个参数类型分别实现该 trait。需要由实现决定唯一关联类型时,用关联类型可让接口更自然。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 高级特性 Advanced Traits · 查看原书依据
With associated types, we don’t need to annotate types because we can’t implement a trait on a type multiple times. In Listing 19-12 with the definition that uses associated types, we can choose what the type of Item will be only once because there can be only one impl Iterator for Counter.
参考来源
- 位置:《The Rust Programming Language(第2版)》第19章 高级特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c19.xhtml`,块 0131)
- 结论依据:原文比较 Iterator 的 Item 与假想泛型定义,说明单个实现只确定一次 Item。
- 原始内容:With associated types, we don’t need to annotate types because we can’t implement a trait on a type multiple times. In Listing 19-12 with the definition that uses associated types, we can choose what the type of Item will be only once because there can be only one impl Iterator for Counter.