11

I'm trying to test some code which takes a reader. I've got a function:

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

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

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

But compiler disagrees:

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

Why? I explicitly said &mut.

Using rust 1.2.0

1 Answer 1

14

You are trying to invoke next_byte::<[u8]>, but [u8] does not implement Read. [u8] and &'a [u8] are not the same type! [u8] is an unsized array type and &'a [u8] is a slice.

When you use the Read implementation on a slice, it needs to mutate the slice in order for the next read to resume from the end of the previous read. Therefore, you need to pass a mutable borrow to a slice.

Here's 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); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.