I am trying to create a method that takes the input from stdin. It should loop until the input is a valid integer that I can parse to an integer. The error I am getting is this:
error[E0282]: type annotations needed for `Result<F, _>`
--> src/lib.rs:9:13
|
9 | let parsed_int_result = line.trim().parse(); // Getting the error here
| ^^^^^^^^^^^^^^^^^
|
help: consider giving `parsed_int_result` an explicit type, where the placeholders `_` are specified
|
9 | let parsed_int_result: Result<F, _> = line.trim().parse(); // Getting the error here
| ++++++++++++++
I think the match statement is kind of wrong, but I dont know how I should solve it. I just want to catch the Err() and try again until the Result-Value is Ok().
pub fn input_int_with_message(msg: &str) -> i32 {
let mut parsed_int;
println!("{msg}");
loop {
let mut line = String::new();
std::io::stdin()
.read_line(&mut line)
.expect("Couldn't read from stdin");
let parsed_int_result = line.trim().parse(); // Getting the error here
let parsed_int = match parsed_int_result {
Ok(integer) => {
integer;
break;
},
Err(error) => println!("Input was not an integer. Try again:"),
};
}
parsed_int
}
>Solution :
Your code declares let mut parsed_int at the top and returns it at the bottom, but let parsed_int = ... in the loop shadows the outer variable. It’s not actually assigning to the outer parsed_int, which prevents Rust from inferring that the inner parsed_int is i32.
As it happens, you don’t actually need a parsed_int variable. You can use break integer to cause the loop to evaluate to integer. Since the loop is the last expression in the function, that will cause the function to effectively return integer. Rust is then able to infer that integer is i32.
pub fn input_int_with_message(msg: &str) -> i32 {
println!("{msg}");
loop {
let mut line = String::new();
std::io::stdin()
.read_line(&mut line)
.expect("Couldn't read from stdin");
let parsed_int_result = line.trim().parse(); // Getting the error here
match parsed_int_result {
Ok(integer) => {
break integer;
}
Err(_) => println!("Input was not an integer. Try again:"),
}
}
}