1

Here's a modified example from Rust by Example:

fn main() {
    // let strings = vec!["tofu", "93", "18"];
    let strings = vec!["93", "18"];
    let possible_numbers: Result<Vec<i32>, std::num::ParseIntError> = strings
        .into_iter()
        .map(|s| s.parse::<i32>())
        .collect();
    let possible_numbers = possible_numbers.unwrap();
    // [93, 18]
    println!("Results: {:?}", possible_numbers);
}

playground

How can I rewrite it such that unwrap will be in a single chain with the other operators?

If I just add unwrap() (to that operator chain) I receive a compile error:

error[E0282]: type annotations needed, cannot infer type for `B`
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
James Larkin
  • 541
  • 5
  • 18

1 Answers1

3

.collect() needs a type annotation somewhere in this context. If it can't get it from the annotation to the variable (which it can't when it's hidden behind the unwrap), you need to use the turbofish style of adding the type annotation. The following code works: (playground link)

fn main() {
    // let strings = vec!["tofu", "93", "18"];
    let strings = vec!["93", "18"];
    let possible_numbers = strings
        .into_iter()
        .map(|s| s.parse::<i32>())
        .collect::<Result<Vec<i32>, std::num::ParseIntError>>()
        .unwrap();
    println!("Results: {:?}", possible_numbers);
}

Edit: see also this blog post for more info on the turbofish operator.