How to pass anonymous functions as parameters in Rust?

半世苍凉 提交于 2019-11-30 11:56:26
A.B.

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

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

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

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

You may also want to take 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!");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!