Type must be known in this context when using Iterator::collect

孤街醉人 提交于 2020-01-09 03:50:06

问题


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
}

fn main() {}
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 that error?


回答1:


On an iterator, the collect method can produce many types of collections:

fn collect<B>(self) -> B
where
    B: FromIterator<Self::Item>, 

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().

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.


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.



来源:https://stackoverflow.com/questions/30972047/type-must-be-known-in-this-context-when-using-iteratorcollect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!