知识卡片

结构图卡 · 6074.d.1.b.1

超trait约束共同能力

理解等级:中级

Shape:Draw要求实现Shape的类型同时实现Draw,使Shape默认方法可使用bounds。它不是传统对象字段与实现的继承。原书所述&dyn Shape无法转为&dyn Draw是1.70限制;Rust1.86已稳定trait对象向上转换,应按项目最低版本判断。

版本依据:Rust1.86发布说明,2026-10-27查阅。

结构图:

classDiagram
class Draw {
  <<trait>>
  +bounds(&self) Bounds
}
class Shape {
  <<trait>>
  +render_in(&self, bounds: Bounds)
  +render(&self)
}
Shape ..> Draw : supertrait约束

依赖箭头表示同时具备Draw能力;render的默认实现使用bounds计算可见区域,再调用render_in。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 2. Traits More Trait Bounds · 查看原书依据

      trait Shape: Draw { /// Render that portion of the shape that falls within `bounds`. fn render_in(&self, bounds: Bounds); /// Render the shape. fn render(&self) { // Default implementation renders that portion of the shape // that falls within the screen area. if let Some(visible) = overlap(SCREEN_BOUNDS, self.bounds()) { self.render_in(visible); } } } In th

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第2章《More Trait Bounds》(spine6;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch02.html;u072-ch02-019)。 - 结论依据:原文在“trait Shape: Draw”附近的定义、例子或代码支撑本卡核心说明:Shape:Draw要求实现Shape的类型同时实现Draw,使Shape默认方法可使用bounds。边界按已读前提解释;示例未执行。 - 原始内容:trait Shape: Draw { /// Render that portion of the shape that falls within `bounds`. fn render_in(&self, bounds: Bounds); /// Render the shape. fn render(&self) { // Default implementation renders that portion of the shape // that falls within the screen area. if let Some(visible) = overlap(SCREEN_BOUNDS, self.bounds()) { self.render_in(visible); } } } In th