知识卡片
行为要求优先写成接口
调用方若依赖某种行为,应把它编码为trait或语义标记,而不是解析类型名称或试探字段。需按字段生成样板时可考虑编译期宏;只在确需异质类型识别时采用Any。这样把可用能力留给编译检查,也避免把运行时探测当作常规接口。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 3. Concepts Item 19: Avoid reflection · 查看原书依据
Prefer interfaces to reflection.” If code needs to rely on the availability of certain behavior for an item, encode that behavior as a trait (Item 2). Even if the desired behavior can’t be expressed as a set of method signatures, use marker traits to indicate compliance with the desired behavior—it’s safer and more efficient than (say) introspecting the name
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第3章《Item 19: Avoid reflection》(spine7;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch03.html;u107-ch03-048)。
- 结论依据:原文在“Prefer interfaces to reflection”附近的定义、例子或代码支撑本卡核心说明:调用方若依赖某种行为,应把它编码为trait或语义标记,而不是解析类型名称或试探字段。边界按已读前提解释;示例未执行。
- 原始内容:Prefer interfaces to reflection.” If code needs to rely on the availability of certain behavior for an item, encode that behavior as a trait (Item 2). Even if the desired behavior can’t be expressed as a set of method signatures, use marker traits to indicate compliance with the desired behavior—it’s safer and more efficient than (say) introspecting the name