Struggling with a placeholder type

⚓ rust    📅 2025-05-22    👤 surdeus    👁️ 3      

surdeus

Warning

This post was published 38 days ago. The information described in this article may have changed.
use std::io;

fn main() {
    let mut user_input = String::new();

    io::stdin()
        .read_line(&mut user_input)
        .and_then(|_| user_input.trim().parse::<i32>())
        .and_then(|number: i32| {
            println!("You entered: {number}");
            Ok(())
        })
        .expect("Unable to parse input into an integer");
}
error[E0308]: mismatched types
 --> src/main.rs:8:23
  |
8 |         .and_then(|_| user_input.trim().parse::<i32>())
  |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Result<_, Error>`, found `Result<i32, ParseIntError>`
  |
  = note: expected enum `Result<_, std::io::Error>`
             found enum `Result<i32, ParseIntError>`
help: try wrapping the expression in `Ok`
  |
8 |         .and_then(|_| Ok(user_input.trim().parse::<i32>()))
  |                       +++                                +

For more information about this error, try `rustc --explain E0308`.
error: could not compile `variables` (bin "variables") due to 1 previous error

Just trying to parse a number from the user so that I can do some calculations with it (the Fibonacci exercise).

I can't understand the reason for the error. It is my understanding that at line 8, I need to specify what type I expect after parsing. I wouldn't expect to need to specify the type for the parameter in the closure on line 9 but even after being explicit, the code still doesn't work.

4 posts - 3 participants

Read full topic

🏷️ rust_feed