How can I specify the type of a closure argument?

天涯浪子 提交于 2020-01-24 19:25:28

问题


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

I've tried moving the slice name a around, but couldn't find the sweet spot of the compiler's understanding.


回答1:


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

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


来源:https://stackoverflow.com/questions/41394751/how-can-i-specify-the-type-of-a-closure-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!