特征可以为它继承的特征的方法提供默认实现吗? [英] Can a trait give a default implementation for the method of a trait that it inherits from?

查看:14
本文介绍了特征可以为它继承的特征的方法提供默认实现吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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::xyforDongDung的实现中输入相同的代码。

推荐答案

用所有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()
    }
}

这篇关于特征可以为它继承的特征的方法提供默认实现吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆