- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
原谅我的“面向对象”心态(对于“面向对象”的某些值(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/
我来自 Asp.Net 世界,试图理解 Angular State 的含义。 什么是 Angular 状态?它类似于Asp.Net中的ascx组件吗?是子页面吗?它类似于工作流程状态吗? 我听到很多人
我一直在寻找 3 态拨动开关,但运气不佳。 基本上我需要一个具有以下状态的开关: |开 |不适用 |关 | slider 默认从中间开始,一旦用户向左或向右滑动,就无法回到N/A(未回答)状态。 有人
我是一名优秀的程序员,十分优秀!