雖然@ Jon使用ncurses的解決方案有效,但ncurses按設計清除了屏幕。我想出了這個解決方案,它使用termios crate作爲我的小項目來學習Rust。這個想法是通過termios綁定訪問tcsetattr
修改ECHO
和ICANON
標誌。的讀取單個字節
extern crate termios;
use std::io;
use std::io::Read;
use std::io::Write;
use termios::{Termios, TCSANOW, ECHO, ICANON, tcsetattr};
fn main() {
let stdin = 0; // couldn't get std::os::unix::io::FromRawFd to work
// on /dev/stdin or /dev/tty
let termios = Termios::from_fd(stdin).unwrap();
let mut new_termios = termios.clone(); // make a mutable copy of termios
// that we will modify
new_termios.c_lflag &= !(ICANON | ECHO); // no echo and canonical mode
tcsetattr(stdin, TCSANOW, &mut new_termios).unwrap();
let stdout = io::stdout();
let mut reader = io::stdin();
let mut buffer = [0;1]; // read exactly one byte
print!("Hit a key! ");
stdout.lock().flush().unwrap();
reader.read_exact(&mut buffer).unwrap();
println!("You have hit: {:?}", buffer);
tcsetattr(stdin, TCSANOW, & termios).unwrap(); // reset the stdin to
// original termios data
}
一個優點是捕獲箭頭鍵,CTRL等擴展F鍵不捕獲(雖然可以ncurses的捕捉這些)。
此解決方案適用於類UNIX平臺。我沒有使用Windows的經驗,但根據此forum,在Windows中使用SetConsoleMode
也許可以實現類似的功能。
這是一個平臺問題,而不是語言問題。在Windows上有字符輸入功能,但在Unix/Linux上,你必須使終端不在線緩衝模式。 – 2014-10-12 03:42:44
您可以使用所提到的SO鏈接中的'getch'功能。你只需要將它編譯成一個共享對象,並從Rust中使用它:https://gist.github.com/ihrwein/a4558d63d9250ee0bbf6你需要一個C編譯器,它只能在Linux上工作(至少我在那裏測試過) 。 – 2016-01-05 19:50:16