3.2.1 实现 Trait
01-实现 Trait — Comprehensive Rust
1分钟内可阅读完
译文 · 基于 Comprehensive Rust
原文链接: https://google.github.io/comprehensive-rust/methods-and-traits/traits/implementing.html
3.2.1 实现 Trait
| |
要为
Type实现Trait,使用impl Trait for Type { .. }块。与 Go 的接口不同:仅仅方法签名匹配还不够——带
talk()方法的Cat类型不会自动满足Pet,除非写在impl Pet块中。Trait 可以为部分方法提供默认实现。默认实现可以依赖该 trait 的所有方法。本例中提供了
greet,它依赖talk。同一类型允许有多个
impl块,包括固有impl与 traitimpl。同样,同一类型也可以实现多个 trait(而且类型常常实现许多 trait!)。impl块甚至可以分散在多个模块/文件中。