特征可以为其继承的特征的方法提供默认实现吗?

Can a trait give a default implementation for the method of a trait that it inherits from?

我有几个方法的特点。一些但不是所有实现此特征的结构都具有其中一种方法的相同实现:

trait Blabla {
    fn xy(self, x: u32, y: u32) -> u32;
}

// ---------------------------------
struct Ding {}

impl Blabla for Ding {
    fn xy(self, x: u32, y: u32) -> u32 {
        x + y
    }
}

// ---------------------------------
struct Dong {
    dong_attribute: u32,
}

impl Dong {
    fn get_1(self) -> u32 {
        1
    }
}

impl Blabla for Dong {
    fn xy(self, x: u32, y: u32) -> u32 {
        x + y + self.get_1()
    }
}

// ---------------------------------
struct Dung {
    dung_attribute: f32,
}

impl Dung {
    fn get_1(self) -> u32 {
        1
    }
}

impl Blabla for Dung {
    fn xy(self, x: u32, y: u32) -> u32 {
        x + y + self.get_1()
    }
}

该示例中有三个结构,每个都实现了 Blabla 特征,其中两个以完全相同的方式实现了 xy 方法。

有没有办法让他们共享该功能的代码?

我正在考虑从 Blabla 继承的第二个特征,并提供 xy 作为该特征的默认实现,如下所示:

trait Blabla {
    fn xy(self, x: u32, y: u32) -> u32;
}

// ----------------------------------
trait Blubblub: Blabla {
    fn get_1(self) -> u32;
    fn xy(self, x: u32, y: u32) -> u32 {
        x + y + self.get_1()
    }
}

// ---------------------------------
struct Ding {}

impl Blabla for Ding {
    fn xy(self, x: u32, y: u32) -> u32 {
        x + y
    }
}

// ---------------------------------
struct Dong {
    dong_attribute: u32,
}

impl Blubblub for Dong {
    fn get_1(self) -> u32 {
        1
    }
}

// ---------------------------------
struct Dung {
    dung_attribute: f32,
}

impl Blubblub for Dung {
    fn get_1(self) -> u32 {
        1
    }
}

fn main() {
    let x = Dung {
        dung_attribute: 1.0,
    };
    println!{"{}", x.xy(1,1)};
}

这是行不通的,因为 Rust 中的特征继承意味着需要实现两个特征,因此它并不能避免我在 Blabla::xy 的实现中为 [=17] 键入相同的代码=] 和 Dung

使用所有 Blubblub 的默认实现实现 Blabla,您的示例有效:

trait Blubblub: Blabla {
    fn get_1(self) -> u32;
}

impl<T: Blubblub> Blabla for T {
    fn xy(self, x: u32, y: u32) -> u32 {
        x + y + self.get_1()
    }
}