知识卡片
泛型实现可替代宏
扩展 trait 可为一组已有类型增加同名方法。先定义 trait 表达能力,再用 blanket impl 对所有满足某约束的类型给出一份实现。原书让所有实现 Copy 的类型得到 hello,数值和布尔值因此可以共用该方法。需要按字段结构生成不同语法或修改现有声明时,这种共享实现的表达范围有限。
相关卡片 [[何时值得写宏]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Going meta 宏的选型与使用边界 · 查看原书依据
And generic functions are a great tool for avoiding duplication, so they offer a valid alternative. Similarly, generic implementation blocks—or blanket implementations—are very powerful. Just look at the crazy piece of code in listing 1.2, an example of the “extension trait” pattern, combining a custom trait with a blanket implementation. We implement our trait for everything that implements Copy.
参考来源
- 位置:《Write Powerful Rust Macros》第01章《Going meta》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-1.xhtml#p32)
- 结论依据:书中示例用 Copy 约束的宽泛实现对比了宏与泛型的去重手段。
- 原始内容:And generic functions are a great tool for avoiding duplication, so they offer a valid alternative. Similarly, generic implementation blocks—or blanket implementations—are very powerful. Just look at the crazy piece of code in listing 1.2, an example of the “extension trait” pattern, combining a custom trait with a blanket implementation. We implement our trait for everything that implements Copy.