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

前端 未结 1 1384
花落未央
花落未央 2020-12-02 00:52

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.coll         


        
相关标签:
1条回答
  • 2020-12-02 01:34

    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.

    0 讨论(0)
提交回复
热议问题