特征可以作为 Fn 引用或闭包传递吗
Can a trait be passed as a Fn reference or closure
在 Rust 中,您可以将对 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
调用作为默认函数实现,但我没能成功。
这在稳定的 Rust 上是不可能的,因为确切的 definition of the Fn
特性是不稳定的。
在 nightly Rust 上,您可以实现 Fn
特性,但仅限于具体类型,因此它不是很有用。
impl<'a> std::ops::Fn<()> for MyRunnable {
extern "rust-call" fn call(&self, ():()) {
self.run();
}
}
在 Rust 中,您可以将对 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
调用作为默认函数实现,但我没能成功。
这在稳定的 Rust 上是不可能的,因为确切的 definition of the Fn
特性是不稳定的。
在 nightly Rust 上,您可以实现 Fn
特性,但仅限于具体类型,因此它不是很有用。
impl<'a> std::ops::Fn<()> for MyRunnable {
extern "rust-call" fn call(&self, ():()) {
self.run();
}
}