Skip to content

Instantly share code, notes, and snippets.

@alihoseiny
Created July 30, 2019 15:55
Show Gist options
  • Save alihoseiny/2bf05d40834c63e6b502c68556ba03c4 to your computer and use it in GitHub Desktop.
Save alihoseiny/2bf05d40834c63e6b502c68556ba03c4 to your computer and use it in GitHub Desktop.
Simple Example of getting an integer from Command line in the Rust
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