tac*_*cos 4 functional-programming rust
我有时会发现自己在C#中编写部分实现的抽象类:
abstract public class Executor {
abstract protected bool Before();
abstract protected bool During();
abstract protected bool After();
protected bool Execute() {
var success = false;
if (Before()) {
if (During()) {
if (After()) {
success = true;
}
}
}
return success;
}
}
Run Code Online (Sandbox Code Playgroud)
尽管有这样一种控制结构的智慧,我如何在像rust这样的函数式语言中实现这一点(部分共享实现)?
在traits上使用默认方法是一种方式(并且很可能/希望将来成为惯用方法;直到最近,struct@ with-closures方法@Slartibartfast演示才是实际工作的唯一方法):
#[allow(default_methods)];
trait Executable {
fn before(&self) -> bool;
fn during(&self) -> bool;
fn after(&self) -> bool;
fn execute(&self) -> bool {
self.before() && self.during() && self.after()
}
}
impl Executable for int {
fn before(&self) -> bool { *self < 10 }
fn during(&self) -> bool { *self < 5 }
fn after(&self) -> bool { *self < 0 }
// execute is automatically supplied, if it is not implemented here
}
Run Code Online (Sandbox Code Playgroud)
请注意,此时可能Executable会覆盖一个实现execute(我已经打开了一个有关#[no_override]禁用此属性的属性的问题).
此外,默认方法是实验性的,并且容易导致编译器崩溃(是的,比Rust的其余部分更多),但它们正在迅速改进.