生锈时,您可以将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
调用作为默认函数实现,但我没有设法使其正常工作。
答案 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();
}
}