rust - 逐个字符读取输入

标签 rust

我有以下函数,可以通过char读取用户输入char。通过在数组中缓冲 char,我想要一个字符串,但到目前为止失败并出现错误:

expected 'char', found enum termion::event::Key

fn readtest() {
    let terminal = io::stdout().into_raw_mode();
    let mut stdout = terminal.unwrap();

    // Use asynchronous stdin
    let mut stdin = termion::async_stdin().keys();
    let mut s = String::new();

    loop {
        // Read input (if any)
        let input = stdin.next();

        // If a key was pressed
        if let Some(Ok(key)) = input {
            match key {
                // Exit if 'q' is pressed
                termion::event::Key::Char('q') => break,
                // Else print the pressed key
                _ => {
                    s.push(key);
                    stdout.lock().flush().unwrap();
                }
            }
        }
        thread::sleep(time::Duration::from_millis(50));
    }
    s
}

最佳答案

s 是一个String,key 是一个Char(char)。您不能直接将 key 插入 s。您首先需要使用如下匹配模式:

 if let termion::event::Key::Char(k) = key {
       s.push(k);
 }

关于rust - 逐个字符读取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64662112/

相关文章:

rust - UDP服务器示例如何安全?

arrays - 如何将数组传递给 Rust 中的函数并更改其内容?

rust - 初始化期间类型不明确

rust - Rust 的内置目标规范在哪里定义?

rust - 如何在 Rust 的同一个 lib.rs 文件中的测试中引用常量?

Rust 闭包错误 -> ...由当前函数拥有 |捕获移动值 :

rust - 默认的通用实现中可能存在错误?

rust - "expected type ` ( )`"在匹配表达式中意味着什么?

memory - 在结构中创建安全的重叠/联合字段

rust - "Expecting a type here because of type ascription"