【问题标题】:How to pass anonymous functions as parameters in Rust?如何在 Rust 中将匿名函数作为参数传递?
【发布时间】:2014-08-07 12:28:08
【问题描述】:

上周我一直在玩Rust。我似乎无法弄清楚如何在调用方法时传递定义为参数的函数,并且没有遇到任何文档显示它们以这种方式使用。

Rust中调用函数时是否可以在参数列表中定义函数?

这是我迄今为止尝试过的......

fn main() {

    // This works
    thing_to_do(able_to_pass);

    // Does not work
    thing_to_do(fn() {
        println!("found fn in indent position");
    });

    // Not the same type
    thing_to_do(|| {
        println!("mismatched types: expected `fn()` but found `||`")
    });
}

fn thing_to_do(execute: fn()) {
    execute();
}

fn able_to_pass() {
    println!("Hey, I worked!");
}

【问题讨论】:

  • 注意:你可以这样做 fn named() { .... } thing_to_do(named); => Rust 允许你在本地范围内声明函数。

标签: function-pointers anonymous-function rust


【解决方案1】:

在 Rust 1.0 中,闭包参数的语法如下:

fn main() {
    thing_to_do(able_to_pass);

    thing_to_do(|| {
        println!("works!");
    });
}

fn thing_to_do<F: FnOnce()>(func: F) {
    func();
}

fn able_to_pass() {
    println!("works!");
}

我们定义了一个泛型类型,受限于以下闭包特征之一:FnOnceFnMutFn

与 Rust 中的其他地方一样,您可以使用 where 子句代替:

fn thing_to_do<F>(func: F) 
    where F: FnOnce(),
{
    func();
}

您可能还想参加a trait object instead:

fn main() {
    thing_to_do(&able_to_pass);

    thing_to_do(&|| {
        println!("works!");
    });
}

fn thing_to_do(func: &Fn()) {
    func();
}

fn able_to_pass() {
    println!("works!");
}

【讨论】:

  • 为什么?因为函数没有环境,而闭包有,因此将函数转换为闭包(添加空环境)很简单,而反过来则要复杂得多(我认为需要蹦床)。
  • thing_to_do 拥有func 的所有权,这意味着func 不能在调用者中重复使用。我已经做了一些工作以使其可使用 &amp; 重用,但是我仍然不知道如何使 apply 函数在任何类型和 FnOnce, Fn, FnMut 变体中通用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-20
  • 2019-11-23
  • 2011-05-11
  • 1970-01-01
  • 2012-09-10
  • 2016-07-23
  • 1970-01-01
相关资源
最近更新 更多