0

我正在尝试Read从切片创建一个特征对象u8,以便在murmur3板条箱中使用,就像这样

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;
}

但我明白了

<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

这段代码有什么问题?

4

1 回答 1

7

Read正如错误消息告诉你的那样,有一个&[u8]. 没有理由使用Readimpl &mut[u8],因此您可以删除mut代码中的一些 's:

// 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;
于 2016-06-17T12:20:35.773 回答