有时候我想从
std::io::Read
中读取单个字节。如果我尝试这样做: Sometimes I want to read a single byte from a std::io::Read
er. If I try to do this:
有时候我想要从std::io::Read
中读取单个字节。如果我试图这样做:
use std::io::{self, Read};
fn main() {
let mut byte: u8 = 0;
io::stdin().read(&mut byte).unwrap();
println!("byte: {}", byte);
}
我遇到了以下错误(很明显,因为byte
不是一个切片):
我遇到了以下错误(很明显,因为byte
不是一个切片):
error[E0308]: mismatched types
--> src/main.rs:6:22
|
6 | io::stdin().read(&mut byte).unwrap();
| ^^^^^^^^^ expected slice, found u8
|
= note: expected type `&mut [u8]`
found type `&mut u8`
有没有办法把 byte
作为简单的 u8
并只取其中一部分,然后将其传递给 read()
?让这段代码工作的明显方法是使用长度为1的数组:
use std::io::{self, Read};
fn main() {
let mut byte: [u8; 1] = [0];
io::stdin().read(&mut byte).unwrap();
println!("byte: {}", byte[0]);
}
但是这在代码的其他部分中有点奇怪的感觉,使用单个的u8
而不是我必须索引的[u8; 1]
会更自然。
如果无法从简单的u8
创建一个切片,那也没关系,但我不知道是否可能,希望能知道一下。
byte[0]
存入另一个变量并使用它。 - Ry-