知识卡片
Sized方法可排除动态调用
在方法上添加where Self:Sized,可把返回Self等操作限定给具体已知大小的类型,而不必禁止整个trait成为dyn对象。Stamp的make_copy可由具体实现调用,却不能经&dyn Stamp调用。方法不可动态调用与trait不可用作动态接口是不同层次。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 2. Traits Trait Object Safety · 查看原书依据
fn make_copy(&self) -> Self where Self: Sized; } let square = Square { top_left: Point { x: 1, y: 2 }, size: 2, }; // `Square` implements `Stamp`, so it can call `make_copy()`. let copy = square.make_copy(); // Because the `Self`-returning method has a `Sized` trait bound, // creating a `Stamp` trait object is possible. let stamp: &dyn Stamp = □ This
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第2章《Trait Object Safety》(spine6;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch02.html;u073-ch02-021)。
- 结论依据:原文在“fn make_copy(&self) -> Self”附近的定义、例子或代码支撑本卡核心说明:在方法上添加where Self:Sized,可把返回Self等操作限定给具体已知大小的类型,而不必禁止整个trait成为dyn对象。边界按已读前提解释;示例未执行。
- 原始内容:fn make_copy(&self) -> Self where Self: Sized; } let square = Square { top_left: Point { x: 1, y: 2 }, size: 2, }; // `Square` implements `Stamp`, so it can call `make_copy()`. let copy = square.make_copy(); // Because the `Self`-returning method has a `Sized` trait bound, // creating a `Stamp` trait object is possible. let stamp: &dyn Stamp = □ This