知识卡片

普通读书笔记卡 · 6074.d.1.a.2.a.1

类型擦除支持异质集合

理解等级:高级

Vec<&dyn Shape>可同时保存Square和Circle引用,遍历时统一调用render,无需知道每个具体类型。共同接口换来了类型信息擦除,也限制了可直接访问的能力。若扩展到动态加载插件,还需单独设计生命周期与ABI兼容,不能仅因有dyn就保证二进制互通。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 2. Traits Trade-Offs · 查看原书依据

      collections of heterogeneous objects—because the code just relies on the methods of the trait, it can invoke and combine the methods of items that have different concrete types. The traditional OO example of rendering a list of shapes is one example of this: the same render() method could be used for squares, circles, ellipses, and stars in the same loop: le

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第2章《Trade-Offs》(spine6;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch02.html;u074-ch02-022)。 - 结论依据:原文在“collections of heterogeneous objects”附近的定义、例子或代码支撑本卡核心说明:Vec<&dyn Shape>可同时保存Square和Circle引用,遍历时统一调用render,无需知道每个具体类型。边界按已读前提解释;示例未执行。 - 原始内容:collections of heterogeneous objects—because the code just relies on the methods of the trait, it can invoke and combine the methods of items that have different concrete types. The traditional OO example of rendering a list of shapes is one example of this: the same render() method could be used for squares, circles, ellipses, and stars in the same loop: le