问题描述
我想得到一个我分割的字符串的长度:
I want to get a length of a string which I've split:
fn fn1(my_string: String) -> bool {
let mut segments = my_string.split(".");
segments.collect().len() == 55
}
error[E0282]: type annotations needed
--> src/lib.rs:3:14
|
3 | segments.collect().len() == 55
| ^^^^^^^ cannot infer type for type parameter `B` declared on the associated function `collect`
|
= note: type must be known at this point
之前的编译器版本报错:
Previous compiler versions report the error:
error[E0619]: the type of this value must be known in this context
--> src/main.rs:3:5
|
3 | segments.collect().len() == 55
| ^^^^^^^^^^^^^^^^^^^^^^^^
我该如何解决这个错误?
How can I fix this error?
推荐答案
关于迭代器,collect
方法 可以产生多种类型的集合:
On an iterator, the collect
method can produce many types of collections:
fn collect<B>(self) -> B
where
B: FromIterator<Self::Item>,
实现 FromIterator
的类型包括 Vec
、String
和 更多.因为有很多可能性,所以需要限制结果类型.您可以使用类似 .collect::<Vec<_>>()
或 let something: Vec<_> 来指定类型.= some_iter.collect()
.
Types that implement FromIterator
include Vec
, String
and many more. Because there are so many possibilities, something needs to constrain the result type. You can specify the type with something like .collect::<Vec<_>>()
or let something: Vec<_> = some_iter.collect()
.
在类型已知之前,您不能调用方法len()
,因为无法知道未知类型是否具有特定方法.
Until the type is known, you cannot call the method len()
because it's impossible to know if an unknown type has a specific method.
如果您纯粹想知道迭代器中有多少项,请使用 Iterator.count()
;为此目的创建向量的效率相当低.
If you’re purely wanting to find out how many items there are in an iterator, use Iterator.count()
; creating a vector for the purpose is rather inefficient.
这篇关于为什么我得到“需要类型注释"?使用 Iterator::collect 时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!