Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

rust - Why do I get "type annotations needed" when using Iterator::collect?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...