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

时间:2014-08-07 12:28:08

标签: 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!");
}

1 个答案:

答案 0 :(得分:10)

在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!");
}
相关问题