1

I'm trying to create a Read trait object from a u8 slice, to use in murmur3 crate, like this

fn main() {
    let mut arr: [u8; 4] = [1, 2, 3, 4];
    let mut slice: &mut [u8] = &mut arr;
    let mut read: &mut std::io::Read = &mut slice;
}

But I get

<anon>:4:42: 4:53 error: the trait `std::io::Read` is not implemented for the type `[u8]` [E0277]
<anon>:4     let mut read : & mut std::io::Read = & mut slice;
                                                  ^~~~~~~~~~~
<anon>:4:42: 4:53 help: see the detailed explanation for E0277
<anon>:4:42: 4:53 help: the following implementations were found:
<anon>:4:42: 4:53 help:   <&'a [u8] as std::io::Read>
<anon>:4:42: 4:53 note: required for the cast to the object type `std::io::Read`
error: aborting due to previous error

What's wrong with this code?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Mikhail Cheshkov
  • 226
  • 2
  • 14

1 Answers1

7

As the error message tells you, there's a Read impl for &[u8]. There's no reason to have a Read impl for &mut[u8], so you can just remove some of the mut's in your code:

// no need for `mut arr`, because `Read` does not modify memory
let arr: [u8; 4] = [1, 2, 3, 4];
// `slice` needs to be `mut`, because `Read` will
// actually make the slice smaller with every step
let mut slice: &[u8] = &arr;
let mut read: &mut std::io::Read = &mut slice;
oli_obk
  • 28,729
  • 6
  • 82
  • 98
  • Thanks! But error message is just strange then. Compiler says "the trait `std::io::Read` is not implemented for the type `[u8]`" when it's actually not implemented for `& mut [u8]` – Mikhail Cheshkov Jun 17 '16 at 12:36
  • 1
    @MikhailCheshkov That's probably because there is a blanked `Read` implementation for `&mut T` where `T: Read`. –  Jun 17 '16 at 12:43