可以将特征作为Fn引用或闭包传递

时间:2016-04-25 07:42:30

标签: rust function-pointers traits

生锈时,您可以将Fn引用为documented

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调用作为默认函数实现,但我没有设法使其正常工作。

1 个答案:

答案 0 :(得分:3)

This is not possible on stable Rust, because the exact definition of the Fn trait is unstable.

On nightly Rust you can implement the Fn traits, but only for concrete types, so it's not very helpful.

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