如何在Rust中将匿名函数作为参数传递?

nat*_*ore 13 function-pointers anonymous-function rust

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!");
}
Run Code Online (Sandbox Code Playgroud)

A.B*_*.B. 12

在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!");
}
Run Code Online (Sandbox Code Playgroud)

我们定义一个泛型类型受限于封闭的特征之一:FnOnce,FnMutFn.

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

fn thing_to_do<F>(func: F) 
    where F: FnOnce(),
{
    func();
}
Run Code Online (Sandbox Code Playgroud)

您可能还想要使用特征对象:

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!");
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么?因为函数在闭包时没有环境,因此将函数转换为闭包(添加空环境)是微不足道的,而反向则要复杂得多(我认为需要蹦床). (4认同)