Rust 1.28+
slice::from_mut back and stable!
use std::{ io::{self, Read}, slice, }; fn main() { let mut byte = 0; let bytes_read = io::stdin().read(slice::from_mut(&mut byte)).unwrap(); if bytes_read == 1 { println!("read byte: {:?}", byte); } }
Rust 1. 0+
But this is a strange feeling in the rest of the code, and it would be more natural to use one u8 rather than [u8; 1] [u8; 1] [u8; 1] [u8; 1] what should I index in.
Creating an array of length 1 would be the most natural way to do this:
use std::io::{self, Read}; fn main() { let mut bytes = [0]; let bytes_read = io::stdin().read(&mut bytes).unwrap(); let valid_bytes = &bytes[..bytes_read]; println!("read bytes: {:?}", valid_bytes); }
However, it is possibly unsafe to create a slice from a reference to a single value:
use std::io::{self, Read}; use std::slice; fn mut_ref_slice<T>(x: &mut T) -> &mut [T] {
Remember that a slice is two things: a pointer to a memory area and a length. With the length part one, you just need to add the length to the mutable link and bam! you got yourself a bite.
Earlier versions of Rust had ref_slice and mut_ref_slice . They were removed because their utility has not yet been proven (this is not a common problem), but they were safe to call. Functions have been moved to the ref_slice box , so if you want to continue using them, this is the only option.
source share