且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-23 08:13:49

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

In Rust 1.0, the syntax for closure parameters is as follows:

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.

We define a generic type constrained to one of the closure traits: FnOnce, FnMut, or Fn.

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

Like elsewhere in Rust, you can use a where clause instead:

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

您可能还想使用 一个 trait 对象:

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