gpt4 book ai didi

rust - 如何在 Rust 中实现多态 mixin-like 行为?

转载 作者:行者123 更新时间:2023-12-03 11:26:33 28 4
gpt4 key购买 nike

原谅我的“面向对象”心态(对于“面向对象”的某些值(value)),但我很难弄清楚如何在 Rust 中创建以下类似物:
在 Python 中,我可以使用抽象/未实现 (raise NotImplementedException) 或默认实现的方法定义基类。然后我可以创建一个 mixin 来覆盖这个基本行为。最后,我可以将基类和 mixin 组合成一个子类,其中 mixin 方法是绑定(bind)到子类的方法。我可以做所有这些来尝试满足与这些对象接口(interface)的另一段代码的接口(interface)要求。我想在 Rust 中做到这一点,而不使用需要相当于 C++ vtables 的动态运行时多态性。在 Python 中,我会使用愚蠢的接口(interface) do_it 执行以下操作:

def do_it(inst):
inst.must_implement_me()

class Base:
def must_implement_me(self):
print('base default implementation')

class Mixin:
def must_implement_me(self):
print('mixin override new default')

class ChildClass(Mixin, Base):
pass



do_it(Base()) # prints "base default implementation"
do_it(ChildClass()) # prints "mixin override new default"
当我尝试在 Rust 中实现相同的目标时:
trait DoIt {
fn must_implement_me(&self);
}

fn do_it<T: DoIt>(inst: T) {
inst.must_implement_me();
}


trait Base {}

impl<T> DoIt for T where T: Base {
fn must_implement_me(&self) {
println!("base default implementation");
}
}

trait Mixin {}
impl<T> DoIt for T where T: Mixin {
fn must_implement_me(&self) {
println!("mixin override new default");
}
}

struct BaseClass();
impl Base for BaseClass{}


struct ChildClass();
impl Base for ChildClass {}
impl Mixin for BaseClass {}


fn main() {
do_it(BaseClass());
do_it(ChildClass());
}
cargo run提示:
error[E0119]: conflicting implementations of trait `DoIt`:
--> src/main.rs:20:1
|
13 | impl<T> DoIt for T where T: Base {
| -------------------------------- first implementation here
...
20 | impl<T> DoIt for T where T: Mixin + Base {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation
有没有办法告诉 Rust Mixin 实现应该获胜?我知道存在歧义,但我可以明确告诉 Rust 哪个方法实现获胜吗?如果没有,还有什么办法可以做到这一点?

最佳答案

上面的代码确实不可能使用rust 。与 python 相比,没有特征边界顺序,因此您无法确定应该调用哪个实现(例如,从 Base 或从 Mixin )。您的特定问题可以通过 trait [ doc link 的默认实现来解决。 ] ( playground ):

trait DoIt {
fn must_implement_me(&self) {
println!("base default implementation");
}
}

// ...

struct BaseClass();
impl Mixin for BaseClass {}

struct ChildClass();
impl DoIt for ChildClass {}
使用夜间功能( playground)可以很快(希望)实现更复杂的静态“重载”:
#![feature(specialization)]

impl<T> DoIt for T {
default fn must_implement_me(&self) {
println!("base default implementation");
}
}

// ...


struct BaseClass();
impl Mixin for BaseClass {}

struct ChildClass();
不过,即使您对夜间编译器没问题,我还是建议您避免使用最后一个代码示例,因为该功能还不完整。

关于rust - 如何在 Rust 中实现多态 mixin-like 行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62579837/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com