【问题标题】:"type annotations needed" / "cannot infer type" when calling Iterator::collect调用 Iterator::collect 时“需要类型注释”/“无法推断类型”
【发布时间】:2015-05-28 11:06:04
【问题描述】:

为什么会这样

fn main() {
    let test = "5% of foo".to_string();
    let result: i32 = test.split('%').collect()[0].parse().unwrap_or(0);
}

导致错误

error[E0282]: type annotations needed
 --> src/main.rs:4:23
  |
4 |     let result: i32 = test.split('%').collect()[0].parse().unwrap_or(0);
  |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type for `B`

这也无济于事:

let result: i32 = test.to_string().split('%').collect()[0].parse().unwrap_or(0i32);

【问题讨论】:

    标签: rust


    【解决方案1】:
    fn main() {
        let test = "5% of foo".to_string();
        let result: i32 = test.split('%').collect::<Vec<_>>()[0].parse().unwrap_or(0);
    }
    

    collect() 可以成为实现FromIterator 的任何类型,因此需要类型提示。

    或者,您可以通过使用惰性迭代器来提高效率。

    fn main() {
        let test = "5% of foo".to_string();
        let result: i32 = test.split('%').next().unwrap_or("0").parse().unwrap_or(0);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-26
      • 2022-08-02
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多