Reputation: 735
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 enumOption
I am not sure how can I specify the type for generic T?
Upvotes: 0
Views: 871
Reputation: 60051
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>);
Upvotes: 4
Reputation: 76489
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.
Upvotes: 1