Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read stdin keys in rust with termion using dynamic char values?

I have the following code to read user input keys from terminal using termion

use std::io::{stdin, stdout};
use termion::event::Key;

fn main() {
    let mut stdout = stdout().into_raw_mode().unwrap();
    let stdin = stdin();
    
    let char_from_config = 'e';

    for c in stdin.keys() {
        match c.unwrap() {
            Key::Char('q') => {
                break;
            }
            Key::Char('h') => {
                // do something
            }
            Key::Char('l') => {
                // do something else
            }
            _ => {}
        }

        stdout.flush().unwrap();
    }
}

What I would want to do is to read not just Key::Char('q') but some other dynamic character value, which I collect from somewhere else, like Key::Char(char_from_config), but it doesn’t work for some reason.

Is there a way to paste a variable containing char instead of an actual 'char' to match arms ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you write a match arm Key(c) => ..., c becomes part of a pattern that match will match against and if value matched this enum variant c will be equal to whatever this variant holds. You however want to say "match only if it’s Key variant with this given value". You have two options how to do it.

  1. You can either have const value (you probably don’t want to do that):
const CHAR_FROM_CONFIG: char = 'e';

match ... {
    Key(CHAR_FROM_CONFIG) => (),
    _ => ()
}
  1. Or use a match guard (you probably do want to do that):
let char_from_config = 'e';

match ... {
    // c will match here any character, but this arm will succeed only
    // when it will be equal to char_from_config 
    Key(c) if c == char_from_config => (),
    _ => ()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading