Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading