2013-07-08 16 views
4

我有時會發現自己寫抽象類與部分實現在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; 
    } 
} 

儘管有這樣的控制結構的智慧,我將如何做到像生鏽的功能語言這個(部分共享實現)?

回答

7

的特質使用默認的方法是單向的(而且很可能/希望是在慣用的方式未來;直到最近,struct -with性關閉方法@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 
} 

注意,這是可能的Executable實現覆蓋execute目前(我已打開an issue#[no_override]屬性,將禁用此)。另外,默認的方法是實驗性的,並且容易造成編譯器崩潰(是的,比Rust的其他部分更加崩潰),但它們正在迅速改進。

3

我不是一個生鏽的編譯器,所以原諒破碎的代碼。

對事物的功能方面,你能有這樣的擁有三項功能的結構,並調用它們

struct Execution { 
    before: @fn() -> bool, 
    during: @fn() -> bool, 
    after: @fn() -> bool 
} 

fn execute (e: Execution) -> bool { 
    ... 
} 

但一旦你有一個函數作爲第一類值,你可以通過說,名單布爾函數來檢查而不是固定的三個,或者其他的東西取決於你想要達到的目標。

對事物鏽面,可以使更多的「面向對象」的使用特性

trait Executable { 
    fn execute(&self); 
} 

impl Execution { 
    fn execute(&self) { 
     ... 
    } 
}