简体   繁体   中英

How can I specify the type of a closure argument?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM