特征可以为父特征的*一些*方法提供默认实现吗? [英] Can a trait give default implementation for *some* methods of a parent trait?

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

问题描述

假设我们有一个基本属性和一个高级属性,如下所示:

pub trait BasicTrait {
    fn key_method(&self);


    fn other_method(&self);
}

pub trait AdvancedTrait: BasicTrait {
    fn key_method_with_argument(&self, parameter: u32);
}
现在,每次有人要实现AdvancedTrait时,BasicTrait::key_method(&self)最有可能的实现是使用一些默认参数调用key_method_with_argument。我如何(惯常地)提供此默认实现,以便实现AdvancedTrait的任何人(1)只需要实现key_method_with_argumentBasicTrait中的任何其他必需方法,以及(2)可选地实现key_method()并仅在需要时覆盖默认实现?

相关问题:

答案here中建议的impl块不起作用,因为代码需要实现BasicTrait的所有其他方法。

推荐答案

您想要的功能名为specialization,不幸的是它只在夜间使用,而且has known soundness holes,所以不要指望它很快就会稳定下来。不过,下面是它的外观:

#![feature(specialization)]

pub trait BasicTrait {
    fn key_method(&self);

    fn other_method(&self);
}

pub trait AdvancedTrait: BasicTrait {
    fn key_method_with_argument(&self, parameter: u32);
}

default impl<T: AdvancedTrait> BasicTrait for T {
    default fn key_method(&self) {
        self.key_method_with_argument(12345);
    }
}

Playground

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

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