简体   繁体   English

如何在 rust 中指定迭代器的类型?

[英]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无法推断枚举Option上声明的类型参数T的类型

I am not sure how can I specify the type for generic T?我不确定如何指定泛型 T 的类型?

The simplest way would be to annotate the type of None directly:最简单的方法是直接注释None的类型:

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 .在这种情况下,您需要调用map始终发出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.编译器通常可以直觉Some(T)的类型,但不能为None ,因为无论选项的类型如何,它都是相同的。

In this case, the easiest way to go about it is to use the turbofish syntax on the map call, like so:在这种情况下,最简单的方法是在map调用中使用 turbofish 语法,如下所示:

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.可以通过为values指定类型来显式指定迭代器类型,但由于迭代器链的类型很快变得非常笨拙,因此在方法上使用 turbofish ( ::<> ) 语法通常更方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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