Rust 程序设计语言简体中文版我们希望使用哪一个。考虑一下示例 19-16 中 的代码,这里定义了 trait Pilot 和 Wizard 都拥有方法 fly 。接着在一个本身已经实现了名 为 fly 方法的类型 Human 上实现这两个 trait。每一个 fly 方法都进行了不同的操作: 文件名:src/main.rs trait Pilot { fn fly(&self); } trait Wizard Wizard { fn fly(&self); } struct Human; impl Pilot for Human { 497/600 Rust 程序设计语言 简体中文版 fn fly(&self) { println!("This is your captain speaking."); } } impl Wizard for Human { 时,编译器默认调用直接实现在类型上的方法,如示例 19-17 所 示。 文件名:src/main.rs # trait Pilot { # fn fly(&self); # } # # trait Wizard { # fn fly(&self); # } # # struct Human; # # impl Pilot for Human { # fn fly(&self) { # println0 码力 | 600 页 | 12.99 MB | 1 年前3
Rust 程序设计语言 简体中文版 1.85.0我们想要使用哪一个。考虑一下示例 20-17 中的代码, 这里我们定义了两个 trait,Pilot 和 Wizard,它们都拥有名为 fly 的方法。接着在一个本身 已经实现了名为 fly 方法的类型 Human 上实现这两个 trait。每一个 fly 方法都进行了不同的 操作: 文件名:src/main.rs trait Pilot { fn fly(&self); } trait Wizard Wizard { fn fly(&self); } struct Human; impl Pilot for Human { fn fly(&self) { println!("This is your captain speaking."); } } impl Wizard for Human { fn fly(&self) { println 调用了直接实现在 Human 上的 fly 方法。 为了能够调用 Pilot trait 或 Wizard trait 的 fly 方法,需要使用更明确的语法来指定具体要调 用的 fly 方法。示例 20-19 演示了这种语法。 文件名:src/main.rs fn main() { let person = Human; Pilot::fly(&person); Wizard::fly(&person);0 码力 | 562 页 | 3.23 MB | 1 月前3
共 2 条
- 1













