我有以下代码使用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'
的变量粘贴到match
arms?
最佳答案
当您编写匹配臂 Key(c) => ...
时,c
成为匹配模式的一部分,如果值与此枚举匹配,则匹配将与之匹配变体 c 将等于该变体所包含的任何内容。然而,您想说“仅当它是具有此给定值的 Key
变体时才匹配”。您有两种选择方法。
- 您可以使用
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/