@@ -21,22 +21,26 @@ use std::{
2121///
2222/// # Returns
2323///
24- /// Returns an `Option<String >` containing the user's input or `None` if the input is empty and
25- /// ` allow_empty` is `false `.
24+ /// Returns an `Option<T >` containing the user's input converted to the specified type,
25+ /// or `None` if the input is empty and ` allow_empty` is `true `.
2626///
2727/// # Example
2828///
2929/// ```no_run
3030/// use console_utils::input;
3131///
32- /// let user_input = input("Enter something: ", false, false);
32+ /// let user_input = input::<String> ("Enter something: ", false, false);
3333///
3434/// match user_input {
3535/// Some(value) => println!("You entered: {}", value),
36- /// None => println !("Input is empty ."),
36+ /// None => panic !("The Input cannot be None, allow_empty is false ."),
3737/// }
3838/// ```
39- pub fn input ( before : & str , allow_empty : bool , new_line : bool ) -> Option < String > {
39+ pub fn input < T > ( before : & str , allow_empty : bool , new_line : bool ) -> Option < T >
40+ where
41+ T : std:: str:: FromStr ,
42+ T :: Err : std:: fmt:: Debug ,
43+ {
4044 loop {
4145 print ! ( "{before} {}" , if new_line { '\n' } else { '\0' } ) ;
4246 io:: stdout ( ) . flush ( ) . unwrap ( ) ;
@@ -47,7 +51,10 @@ pub fn input(before: &str, allow_empty: bool, new_line: bool) -> Option<String>
4751 if allow_empty && cli. trim ( ) . is_empty ( ) {
4852 return None ;
4953 } else if !cli. trim ( ) . is_empty ( ) {
50- return Some ( cli. trim ( ) . to_owned ( ) ) ;
54+ match cli. trim ( ) . parse ( ) {
55+ Ok ( value) => return Some ( value) ,
56+ Err ( _) => println ! ( "\n Wrong Input Type\n " ) ,
57+ }
5158 } else {
5259 println ! ( "\n Wrong Input\n " ) ;
5360 }
@@ -71,7 +78,7 @@ pub fn input(before: &str, allow_empty: bool, new_line: bool) -> Option<String>
7178/// # Returns
7279///
7380/// Returns an `Option<Vec<bool>>` containing a vector of booleans indicating which options were
74- /// selected. Returns `None` if no option was selected and `allow_empty` is `false `.
81+ /// selected. Returns `None` if no option was selected and `allow_empty` is `true `.
7582///
7683/// # Example
7784///
@@ -163,7 +170,7 @@ pub fn select(
163170 reset ( stdout, "" , options. len ( ) ) ;
164171 return Some ( matrix) ;
165172 } else {
166- reset ( stdout, "\n Wrong Input \n " , options. len ( ) ) ;
173+ reset ( stdout, "\n Please Select any option! \n " , options. len ( ) ) ;
167174 }
168175 }
169176}
0 commit comments