Sometimes I want to read a single byte from a std::io::Read
er. If I try to do this:
use std::io::{self, Read};
fn main() {
let mut byte: u8 = 0;
io::stdin().read(&mut byte).unwrap();
println!("byte: {}", byte);
}
I get the following error (which is clear, as byte
is not a slice):
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`
Is there a way I can keep byte
as a simple u8
and just take a slice of it, which I can then pass to read()
? The obvious way to make this code work is to use an array of length 1:
use std::io::{self, Read};
fn main() {
let mut byte: [u8; 1] = [0];
io::stdin().read(&mut byte).unwrap();
println!("byte: {}", byte[0]);
}
But that's kinda weird feeling throughout the rest of the code, and it would be more natural to use a single u8
rather than a [u8; 1]
that I have to index into.
If it's not possible to create a slice from the simple u8
that's okay, but I don't know if it's possible or not and would like to know.