一个特质可以为父特质的*一些*方法提供默认实现吗?

6

假设我们有以下基本特征和高级特征:

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的人只需实现key_method_with_argument和来自BasicTrait的任何其他所需方法,并且只有在需要时才能选择实现key_method()并覆盖默认实现?
相关问题:
此处所建议的那样具有impl块不能正常工作,因为代码希望实现BasicTrait的所有其他方法。

1
你要找的是所谓的“特化”,至少在稳定的 Rust 中是不可用的。 - Chayim Friedman
2个回答

5
你可以通过显式地将 BasicTrait 方法复制到 AdvancedTrait 中,要求用户仅实现 AdvancedTrait,然后对实现 AdvancedTrait 的任何东西进行全局 impl,以使其也实现 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)
    }
}

你也可以称 key_method_implbasic_key_method,还有其他一些命名选项。


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);
    }
}

游乐场


感谢您详细的响应并提供了代码演示! - Amir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接