nat*_*ore 13 function-pointers anonymous-function rust
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!");
}
Run Code Online (Sandbox Code Playgroud)
A.B*_*.B. 12
在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!");
}
Run Code Online (Sandbox Code Playgroud)
我们定义一个泛型类型受限于封闭的特征之一:FnOnce
,FnMut
或Fn
.
与Rust中的其他地方一样,您可以使用where
子句代替:
fn thing_to_do<F>(func: F)
where F: FnOnce(),
{
func();
}
Run Code Online (Sandbox Code Playgroud)
您可能还想要使用特征对象:
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!");
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5080 次 |
最近记录: |