【问题标题】:Why do I get "type annotations needed" when using Iterator::collect?为什么在使用 Iterator::collect 时会出现“需要类型注释”?
【发布时间】:2021-07-26 20:28:04
【问题描述】:

我想得到一个我已经拆分的字符串的长度:

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

以前的编译器版本报错:

error[E0619]: the type of this value must be known in this context
 --> src/main.rs:3:5
  |
3 |     segments.collect().len() == 55
  |     ^^^^^^^^^^^^^^^^^^^^^^^^

我该如何解决这个错误?

【问题讨论】:

    标签: rust


    【解决方案1】:

    在迭代器上,the collect method 可以产生多种类型的集合:

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

    实现FromIterator 的类型包括VecStringmany more。因为有很多可能性,所以需要对结果类型进行约束。您可以使用.collect::&lt;Vec&lt;_&gt;&gt;()let something: Vec&lt;_&gt; = some_iter.collect() 之类的内容指定类型。

    在类型已知之前,您不能调用方法len(),因为无法知道未知类型是否具有特定方法。


    如果您只是想知道迭代器中有多少项,请使用Iterator.count();为此目的创建一个向量是相当低效的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 2017-12-15
      • 1970-01-01
      • 2019-07-22
      • 2018-09-07
      • 1970-01-01
      相关资源
      最近更新 更多