@Faheem Uz Zaman suggested using the text_io crate, which is an excellent option. However, the read!
macro really does exactly what the code in the original question does: reads an input into a string variable and then attempts to parse that string into an i32.
In order to parse input from the terminal into an i32 variable, some error-handling needs to be implemented. The code in the question is complete and handles integer input, so long as the input is indeed an integer.
The text_io crate provides a try_read!
macro which allows for bad input. Here is an example of how to implement the try_read! macro, which requires adding the same type of error handling that could be added to the original question's sample code:
use text_io::*;
fn main() {
let i: i32 = match(try_read!()) {
Ok(integer_read) => integer_read,
Err(bad_string) => {
eprintln!("Error: {}", bad_string);
return;
},
};
println!("{}",i);
}
This could be shortened using the ?
operator, which would require an adjustment to the return value for main():
use text_io::*;
fn main()-> Result<(), Error>{
let i: i32 = try_read!()?;
println!("{}",i);
Ok(())
}
This will print the parsing error message if the input is not parseable to an i32.