如何在Rust中将匿名函数作为参数传递? [英] How to pass anonymous functions as parameters in Rust?

查看:989
本文介绍了如何在Rust中将匿名函数作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去一周我一直在玩Rust.我似乎无法弄清楚如何在调用该方法时传递定义为参数的函数,也没有遇到任何表明它们以这种方式使用的文档.

I've been playing around with Rust the past week. I can't seem to figure out how to pass a function that is defined as a parameter when calling the method, and haven't come across any documentation that shows them being used in that fashion.

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

Is it possible to define a function in the parameter list when calling a function in Rust?

这是我到目前为止尝试过的...

This is what I've tried so far...

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

推荐答案

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

我们定义了一个受限于闭包特征之一的泛型类型: FnOnce FnMut Fn .

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();
}


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

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

这篇关于如何在Rust中将匿名函数作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆