You can call str::parse(), but you need to make sure that read_line is working. We need a reader:
use std::io;
fn main() {
let reader = io::stdin();
}
stdin reads the global buffer that handles the input stream and also implements the BufRead trait which has the read_line method method. This takes a mutable String as an input buffer and reads all bytes from the stream until a newline byte is reached and appends them to the buffer. The #expect() method unwraps the Result; if it is an Err it will panic with the message and the cause.
use std::io;
fn main() {
let reader = io::stdin();
let mut input_text = String::new();
reader.read_line(&mut input_text).expect("failed to read line");
}
We now have the input text that we want to convert into an i32. This is where str::parse() will work for us, as long as we give it a type to parse to. str::trim() is necessary because read_line includes the newline byte the buffer
use std::io;
fn main() {
let reader = io::stdin();
let mut input_text = String::new();
reader.read_line(&mut input_text).expect("failed to read line");
let input = input_text.trim().parse::<i32>();
}
We're not done yet, we still need to ensure that we successfully parsed the input using pattern matching. All the code you need to convert your original input buffer into a usable integer is:
use std::io;
fn main() {
let reader = io::stdin();
let mut input_text = String::new();
reader.read_line(&mut input_text).expect("failed to read line");
let input_opt = input_text.trim().parse::<i32>();
let input_int = match input_opt {
Ok(input_int) => input_int,
Err(e) => {
println!("please input a number ({})", e);
return;
}
};
println!("{}", input_int);
}
This compiles without errors or warnings.