2016-04-25 22 views
0

在鏽傳遞,你可以在一個參照Fndocumented可以性狀爲FN引用或關閉

fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 { 
    some_closure(1) 
} 
let answer = call_with_one(&|x| x + 2); 

但是我想寫一個特點是,如果實行了Runnable可以傳遞給任何期望Fn()的東西。這可能嗎?

trait Runnable { 
    fn run(&self); 
} 

struct MyRunnable; 
impl Runnable for MyRunnable { 
    fn run(&self) {} 
} 

struct StructThatTakesClosure<'life> { 
    closure_field: &'life Fn(), 
} 

fn main() { 
    // is there a way to change the Runnable trait to automatically match the 
    // Fn() interface such that the MyRunnable instance can be passed directly? 
    StructThatTakesClosure { closure_field: &|| MyRunnable.run() }; 
} 

我試圖實現3通常extern電話爲默認功能,但我沒能得到它的工作。

回答

3

這是不可能的穩定鏽,因爲確切的definition of the Fn性狀是不穩定的。

在每晚的Rust上,您可以實現Fn特徵,但僅限於具體類型,所以它不是很有幫助。

impl<'a> std::ops::Fn<()> for MyRunnable { 
    extern "rust-call" fn call(&self,():()) { 
     self.run(); 
    } 
} 
相關問題