如何从输入中读取单个字符作为 u8?

How to read a single character from input as u8?

我目前正在为 this language 构建一个简单的解释器以供练习。唯一需要克服的问题是从用户输入中读取单个字节作为字符。到目前为止,我有以下代码,但我需要一种方法将第二行生成的 String 转换为 u8 或我可以转换的另一个整数:

let input = String::new()
let string = std::io::stdin().read_line(&mut input).ok().expect("Failed to read line");
let bytes = string.chars().nth(0) // Turn this to byte?

以字节为单位的值应该是 u8,我可以将其转换为 i32 以在其他地方使用。也许有更简单的方法来做到这一点,否则我将使用任何有效的解决方案。

首先,使您的输入可变,然后使用 bytes() 而不是 chars()

let mut input = String::new();
let string = std::io::stdin().read_line(&mut input).ok().expect("Failed to read line");
let bytes = input.bytes().nth(0).expect("no byte read");

请注意,Rust 字符串是一系列 UTF-8 代码点,不一定是字节大小的。根据您要实现的目标,使用 char 可能是更好的选择。

只读取一个字节并将其转换为 i32:

use std::io::Read;

let input: Option<i32> = std::io::stdin()
    .bytes() 
    .next()
    .and_then(|result| result.ok())
    .map(|byte| byte as i32);

println!("{:?}", input);