Aykana
Aykana

Reputation: 43

Read input char by char

I have the following function that read the user input char by char. By buffering the char in an array, I would like to have a string but fail so far with the error:

expected 'char', found enum termion::event::Key

fn readtest() {
    let terminal = io::stdout().into_raw_mode();
    let mut stdout = terminal.unwrap();

    // Use asynchronous stdin
    let mut stdin = termion::async_stdin().keys();
    let mut s = String::new();

    loop {
        // Read input (if any)
        let input = stdin.next();

        // If a key was pressed
        if let Some(Ok(key)) = input {
            match key {
                // Exit if 'q' is pressed
                termion::event::Key::Char('q') => break,
                // Else print the pressed key
                _ => {
                    s.push(key);
                    stdout.lock().flush().unwrap();
                }
            }
        }
        thread::sleep(time::Duration::from_millis(50));
    }
    s
}

Upvotes: 2

Views: 975

Answers (1)

edkeveked
edkeveked

Reputation: 18371

s is a String and key is a Char(char). You cannot push directly key into s. You first need to use a matching pattern as follows:

 if let termion::event::Key::Char(k) = key {
       s.push(k);
 }

Upvotes: 2

Related Questions