【发布时间】:2014-08-07 12:28:08
【问题描述】:
上周我一直在玩Rust。我似乎无法弄清楚如何在调用方法时传递定义为参数的函数,并且没有遇到任何文档显示它们以这种方式使用。
在Rust中调用函数时是否可以在参数列表中定义函数?
这是我迄今为止尝试过的......
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!");
}
【问题讨论】:
-
注意:你可以这样做
fn named() { .... } thing_to_do(named);=> Rust 允许你在本地范围内声明函数。
标签: function-pointers anonymous-function rust