input - 如何使用动态字符值读取 Rust 中的标准输入键?

标签 input rust terminal match stdin

我有以下代码使用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();
    }
}

我想要做的不仅仅是读取Key::Char('q'),而是读取一些其他动态字符值,这些值是我从其他地方收集的,例如Key: :Char(char_from_config),但由于某种原因它不起作用。

有没有办法将包含char而不是实际的'char'的变量粘贴到matcharms?

最佳答案

当您编写匹配臂 Key(c) => ... 时,c 成为匹配模式的一部分,如果值与此枚举匹配,则匹配将与之匹配变体 c 将等于该变体所包含的任何内容。然而,您想说“仅当它是具有此给定值的 Key 变体时才匹配”。您有两种选择方法。

  1. 您可以使用 const 值(您可能不想这样做):
const CHAR_FROM_CONFIG: char = 'e';

match ... {
    Key(CHAR_FROM_CONFIG) => (),
    _ => ()
}
  • 或者使用比赛守卫(您可能确实想要这样做):
  • 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 => (),
        _ => ()
    }
    

    关于input - 如何使用动态字符值读取 Rust 中的标准输入键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73983048/

    相关文章:

    javascript - html 输入显示不同的文本到它发布的值

    c中的复数输入

    javascript - 用 JavaScript 改变焦点

    rust - 为什么 Vec::as_slice 和数组强制的生命周期检查不同?

    rust - 如何启用 Rust "crate feature"?

    ruby-on-rails - Sidekiq worker 每两秒显示 'ERROR: heartbeat: "\xE 2"from ASCII-8BIT to UTF-8'

    linux - 在 linux shell 中使用键盘选择文本

    google-chrome - 输入和选择元素在 Chrome + Safari 中添加了填充,但在 Firefox 中没有?

    data-structures - 如何连接向量元素并将其存储回向量?

    linux - 如何制作脚本或程序来运行某些命令?