特征可以为父特征的*某些*方法提供默认实现吗?

Ami*_*mir 6 traits rust

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

pub trait BasicTrait {
    fn key_method(&self);


    fn other_method(&self);
}

pub trait AdvancedTrait: BasicTrait {
    fn key_method_with_argument(&self, parameter: u32);
}
Run Code Online (Sandbox Code Playgroud)

现在,每次有人实现 时AdvancedTrait,最有可能的实现BasicTrait::key_method(&self)key_method_with_argument使用一些默认参数进行调用。我如何(惯用地)提供此默认实现,以便任何实现者AdvancedTrait(1)只需要实现key_method_with_argument中的方法和任何其他所需的方法BasicTrait,以及(2)仅在需要时可选地实现key_method()和覆盖默认实现?

相关问题:

此处impl答案中提出的块不起作用,因为代码预计会实现.BasicTrait

orl*_*rlp 5

您可以通过显式地将BasicTrait方法复制到其中AdvancedTrait,要求您的用户实现AdvancedTrait,然后对所有实现的内容进行全面的AdvancedTrait实现来实现BasicTrait。可能建议为重复的方法指定一个名称,表明它们仅用于实现BasicTrait,并防止不明确的调用:

pub trait BasicTrait {
    fn key_method(&self);
    fn other_method(&self);
}

pub trait AdvancedTrait: BasicTrait {
    fn key_method_impl(&self) {
        self.key_method_with_argument(0)
    }
    fn other_method_impl(&self);


    fn key_method_with_argument(&self, parameter: u32);
}

impl<T: AdvancedTrait> BasicTrait for T {
    fn key_method(&self) {
        AdvancedTrait::key_method_impl(self)
    }
    
    fn other_method(&self) {
        AdvancedTrait::other_method_impl(self)
    }
}
Run Code Online (Sandbox Code Playgroud)

您也可以调用key_method_impl basic_key_method,存在许多命名选项。


Cha*_*man 2

您想要的功能称为“专业化”,不幸的是,它仅限夜间使用,并且存在已知的健全性漏洞,因此不要指望它很快就会稳定下来。然而,它的样子是这样的:

#![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);
    }
}
Run Code Online (Sandbox Code Playgroud)

游乐场