rust - 特征可以作为 Fn 引用或闭包传递吗

标签 rust function-pointers traits

在 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 引用或闭包传递吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36834633/

相关文章:

rust - 为什么我在 "no ` 中收到错误 `executor` block_on` 尝试阻塞异步函数时?

rust - 删除通过出指针发送到C然后传回Rust进行删除的mem::forgotten字符串数组的正确方法是什么?

rust - 使用 writeln 时必须使用的未使用的 `std::result::Result`

c - 基本 C 指针和函数

scala - 更高程度的更高种类?

rust - 如何在 Vector 上为我自己的结构实现 PartialEq?

generics - 是否可以在泛型函数中排除引用参数?

c - 什么 *(DWORD_PTR*)&functionA = functionB( var1, var2);做?

function - 如何将另一个函数返回的函数分配给函数变量?结果而不是生成函数本身

generics - 通用结构的构造函数中的“Expected type parameter”错误