如何在 Rust 中将匿名函数作为参数传递? [英] How to pass anonymous functions as parameters in 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();
}
<小时>
您可能还想使用 一个 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!");
}
这篇关于如何在 Rust 中将匿名函数作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!