在过go 的一周里,我一直在玩Rust个.我似乎不知道如何在调用方法时传递定义为参数的函数,也没有遇到任何文档显示它们以这种方式使用.

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

这就是我到目前为止try 过的...

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中,闭包参数的语法如下:

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

你也可以 Select 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!");
}

Rust相关问答推荐

使用pyo3::Types::PyIterator的无限内存使用量

Rust TcpStream不能在读取后写入,但可以在不读取的情况下写入.为什么?

为什么`Vec i64`的和不知道是`Option i64`?

将数组转换为HashMap的更简单方法

为什么铁 rust S似乎有内在的易变性?

使用极点数据帧时,找不到枚举结果的方法lazy()

告诉Rust编译器返回值不包含构造函数中提供的引用

我可以在不收集或克隆的情况下,将一个带有Item=(key,val)的迭代器拆分成单独的key iter和val iter吗?

将serde_json读入`VEC<;T&>;`( rust 色)时出现问题

如何在嵌套的泛型 struct 中调用泛型方法?

确保参数是编译时定义的字符串文字

在 Rust 中,在第一个空格上分割字符串一次

在 Rust 中查找向量中 dyn struct 的索引

Rust 中指向自身的引用如何工作?

‘&T as *const T as *mut T’ 在 ‘static mut’ 项目中合适吗?

Some(v) 和 Some(&v) 有什么区别?

如何判断服务器是否正确接收数据

如何展平以下嵌套的 if let 和 if 语句?

Rust 中函数的类型同义词

当特征函数依赖于为 Self 实现的通用标记特征时实现通用包装器