Eon*_*nil 5 extension-methods traits rust
在 Swift 中,我可以将扩展方法附加到任何struct,enum或protocol(与traitRust 中相同)。
protocol Foo1 {
    func method1() -> Int 
}
extension Foo1 {
    func method2() {
        print("\(method1())")
    }
}
那么Foo1现在所有符合协议的类型都有method2(). 这对于轻松构建“方法链”非常有用。
如何在 Rust 中做同样的事情?这对错误不起作用。
struct Kaz {}
impl Foo for Kaz {}
trait Foo {
    fn sample1(&self) -> isize { 111 } 
}
impl Foo {
    fn sample2(&self) {
        println!("{}", self.sample1());
    }
}
fn main() {
    let x = Kaz {};
    x.sample1();
    x.sample2();
}
这是错误。
warning: trait objects without an explicit `dyn` are deprecated
  --> src/main.rs:13:6
   |
13 | impl Foo {
   |      ^^^ help: use `dyn`: `dyn Foo`
   |
   = note: `#[warn(bare_trait_objects)]` on by default
error[E0599]: no method named `sample2` found for type `Kaz` in the current scope
  --> src/main.rs:22:7
   |
3  | struct Kaz {}
   | ---------- method `sample2` not found for this
...
22 |     x.sample2();
   |       ^^^^^^^ method not found in `Kaz`
error: aborting due to previous error
在 Rust 中,您可以使用extension traits,这是一个具有通用实现的特性,用于T实现基本特性的所有类型:
struct Kaz {}
impl Foo for Kaz {}
trait Foo {
    fn sample1(&self) -> isize { 111 } 
}
trait FooExt {
    fn sample2(&self);
}
impl<T: Foo> FooExt for T {
    fn sample2(&self) {
        println!("{}", self.sample1());
    }
}
fn main() {
    let x = Kaz {};
    x.sample1();
    x.sample2();
}