2

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 ?

1 Answer 1

2

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 => (),
    _ => ()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.