简体   繁体   中英

How to specify a type for iterator in rust?

When I try running following code

fn main(){
    let a= vec![1,2,3,4,5];
    let values = a.iter().map(|_| None);
    println!("{:?}",values.len());
}

I get following error

cannot infer type for type parameter T declared on the enum Option

I am not sure how can I specify the type for generic T?

The simplest way would be to annotate the type of None directly:

let values = a.iter().map(|_| None as Option<i32>);

or even:

let values = a.iter().map(|_| None::<i32>);

In this case, you have a call to map that always emits None . The compiler can usually intuit the type for Some(T) , but not for None , since it's the same regardless of the type of the option.

In this case, the easiest way to go about it is to use the turbofish syntax on the map call, like so:

fn main() {
    let a = vec![1, 2, 3, 4, 5];
    let values = a.iter().map::<Option<i32>, _>(|_| None);
    println!("{:?}", values.len());
}

Note that in this case, we use _ to let the compiler infer the type of the closure because it's not necessary or convenient to specify. With this hint, the compiler is capable of determining the type of the iterator.

You could also explicitly specify the iterator type by giving a type for values , but because types of iterator chains quickly become extremely unwieldy, it's usually more convenient to use the turbofish ( ::<> ) syntax on a method instead.

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