Caballero
Caballero

Reputation: 12111

"type annotations needed" / "cannot infer type" when calling Iterator::collect

Why does this

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

cause an error

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`

This doesn't help either:

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

Upvotes: 11

Views: 8782

Answers (1)

Manishearth
Manishearth

Reputation: 16198

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

collect() can become any type that implements FromIterator so a type hint is required.

Alternatively, you can make it more efficient by utilizing lazy iterators.

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

Upvotes: 12

Related Questions