How can I specify the type of a closure argument?

2019-08-02 03:03发布

问题:

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


标签: rust closures