Getting a reader for a byte array

I am trying to check the code that takes the reader. I have a function:

fn next_byte<R: Read>(reader: &mut R) -> ... 

How can I test it on some kind of byte array? The docs say that there exists impl<'a> Read for &'a [u8] , which implies that this should work:

 next_byte(&mut ([0x00u8, 0x00][..])) 

But the compiler does not agree:

 the trait `std::io::Read` is not implemented for the type `[u8]` 

Why? I directly said &mut .

Using rust 1.2.0

+5
source share
1 answer

You are trying to call next_byte::<[u8]> , but [u8] does not implement Read . [u8] and &'a [u8] not of the same type! [u8] is the type of the non-standard array, and &'a [u8] is the slice.

When you use the Read implementation on a slice, it must mutate the slice so that the next read resumes from the end of the previous read. So you need to pass volatile borrowing to fragment.

Here is a simple working example:

 use std::io::Read; fn next_byte<R: Read>(reader: &mut R) { let mut b = [0]; reader.read(&mut b); println!("{} ", b[0]); } fn main() { let mut v = &[1u8, 2, 3] as &[u8]; next_byte(&mut v); next_byte(&mut v); next_byte(&mut v); } 
+5
source

Source: https://habr.com/ru/post/1234160/


All Articles