Created
July 30, 2019 15:55
-
-
Save alihoseiny/2bf05d40834c63e6b502c68556ba03c4 to your computer and use it in GitHub Desktop.
Simple Example of getting an integer from Command line in the Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io; | |
fn main() { | |
// Short version without Error handling. If input is not a valid number, program will | |
// exit with error in runtime. | |
let mut user_input_string = String::new(); | |
io::stdin().read_line(&mut user_input_string).unwrap(); | |
let user_input_number = user_input_string.trim().parse::<i32>().unwrap(); // Trims The input for removing white spaces and then parses it as a `i32` number. | |
println!("User number is: {}", user_input_number); | |
// Long Version with Error handling. | |
user_input_string = String::new(); | |
io::stdin().read_line(&mut user_input_string).unwrap(); | |
match user_input_string.trim() .parse::<i32>(){ | |
Ok(user_number) => println!("User number is: {}", user_number), | |
Err(_) => println!("Something is not wrong. Maybe you did not enter a valid integer.") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment