I am currently learning Rust and on my own and need some feedback so I do not get into any bad habits.

This is m first attempt at creating some kind of token for a simple Lottory checker.

The only inputs should be a number between 1 and 59, and Yes an No decision.

#[derive(Debug)]
pub enum Token {
    Number(i32),
    Decision(char),
    Error(String),
}
impl Token {
   pub fn create(value: &String) -> Option<Token> {

        if let Ok(x) = value.parse::<i32>() {
            return Some(Token::Number(x));
        }

        if let Ok(x) = value.parse::<char>() {
            return Some(Token::Decision(x));
        } else {
            None
        }

    }
}

pub fn get_input(msg: &str) -> Token {
    print!("{}\n{}", msg, &PROMPT);
    io::stdout().flush().unwrap();

    let mut buffer = String::new();
    while buffer.is_empty() {

        io::stdin()
            .read_line(&mut buffer)
            .expect("GET_INPUT: error reading line.");

        buffer = buffer
            .trim()
            .parse()
            .expect("GET_INPUT: error parsing buffer");

        if buffer.is_empty() {
            println!("You didn't enter anything.\n{}", &msg)
        };
    }

    if let Some(token) = Token::create(&buffer) {
        token
    } else {
        Token::Error("GET_INPUT: no result".to_string())
    }
}

So the get_input() should return Type Token. and the caller will handle the Error

0 Answers