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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With