知识卡片

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

trait对象支持运行时替换

理解等级:中级

&dyn Trait或Box让调用方按trait接口在运行时使用不同实现,而不把具体类型写死在泛型参数中。由于具体对象大小未知,需要借用或指针等间接形式。trait及其可动态调用的方法必须符合dyn兼容规则;带Self:Sized限制的方法可以排除在该接口外,不能笼统说trait里绝不能出现Self或泛型方法。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 1. Types Trait objects · 查看原书依据

      Trait objects A trait object is the other way to make use of the encapsulation defined by a trait, but here, different possible implementations of the trait are chosen at runtime rather than compile time. This dynamic dispatch is analogous to using virtual functions in C++, and under the covers, Rust has “vtable” objects that are roughly analogous to those i

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Trait objects》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u021-ch01-021)。 - 结论依据:原文在“Trait objects”附近的定义、例子或代码支撑本卡核心说明:&dyn Trait或Box<dyn Trait>让调用方按trait接口在运行时使用不同实现,而不把具体类型写死在泛型参数中。边界按已读前提解释;示例未执行。 - 原始内容:Trait objects A trait object is the other way to make use of the encapsulation defined by a trait, but here, different possible implementations of the trait are chosen at runtime rather than compile time. This dynamic dispatch is analogous to using virtual functions in C++, and under the covers, Rust has “vtable” objects that are roughly analogous to those i