如何指定闭包参数的类型? [英] How can I specify the type of a closure argument?
问题描述
我正在尝试执行类似的操作,但是在 inspect
的闭包参数上无法编译:
I'm trying to do something like this, but it fails to compile on inspect
's closure arguments:
fn main() {
vec!(1, 2, 3, 4)
.windows(2)
.inspect(|&&a[]| println!("{} {}", a[0], a[1]))
.count();
}
我尝试移动切片名称 a
,但找不到编译器理解的最佳途径。
I've tried moving the slice name a
around, but couldn't find the sweet spot of the compiler's understanding.
推荐答案
直接的答案是要使用冒号,就像在其他任何地方都定义参数类型一样:
The direct answer is to use a colon, just like everywhere else you define an arguments type:
fn main() {
vec!(1, 2, 3, 4)
.windows(2)
.inspect(|a: &&[u8]| println!("{} {}", a[0], a[1]))
.count();
}
正如Matthieu M.所指出的,没有理由在此处指定类型因为类型推断完全可以解决它:
As pointed out by Matthieu M., there's no reason to specify a type here at all as type inference will handle it:
fn main() {
vec!(1, 2, 3, 4)
.windows(2)
.inspect(|a| println!("{} {}", a[0], a[1]))
.count();
}
出于完整性考虑,您可以也要指定封闭件的返回类型,尽管这样做需要封闭件主体有大括号。同样,这很少需要:
For completeness, you can also specify the return type of the closure, although doing so requires braces for the closure body. Again, this is rarely needed:
fn main() {
vec!(1, 2, 3, 4)
.windows(2)
.map(|a: &[u8]| -> bool { a[0] % 2 == 0 })
.inspect(|a| println!("{}", a))
.count();
}
这篇关于如何指定闭包参数的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!