1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
use std::io::stdin; use std::str::FromStr; /// Get line as [`std::string::String`] /// /// # Example - Echo utf-8 text /// ``` /// use cli_helper::cli::get_line; /// /// fn echo() { /// println!("Echo: {}", get_line().expect("Your input was likely not UTF-8")) /// } /// ``` pub fn get_line() -> Option<String> { let mut s = String::new(); let res = stdin().read_line(&mut s); s.pop(); match res { Ok(_) => Some(s), Err(_) => None } } /// Get line of any type that can be [`std::str::parse`]d /// /// # Example - Echo signed 32bit integer /// ``` /// use cli_helper::cli::get_line_as; /// /// fn echo_integer() { /// println!("Echo: {}", get_line_as::<i32>().expect("Your input was likely not an integer or was larger than {2^31-1}")) /// } /// ``` pub fn get_line_as<T: FromStr>() -> Option<T> { match get_line() { Some(s) => { match s.parse::<T>() { Ok(t) => Some(t), _ => None } } _ => None } }