【问题标题】:Create Read trait object from u8 slice从 u8 切片创建读取特征对象
【发布时间】:2016-06-17 12:10:43
【问题描述】:

我正在尝试从 u8 切片创建一个 Read 特征对象,以在 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

这段代码有什么问题?

【问题讨论】:

    标签: rust slice trait-objects


    【解决方案1】:

    正如错误消息告诉您的,&amp;[u8] 有一个 Read impl。没有理由为 &amp;mut[u8] 使用 Read impl,因此您可以删除代码中的一些 mut

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

    【讨论】:

    • 谢谢!但是错误信息很奇怪。编译器说“特征std::io::Read 没有为[u8] 类型实现”,而实际上它没有为&amp; mut [u8] 实现
    • @MikhailCheshkov 这可能是因为&amp;mut T 有一个空白的Read 实现,其中T: Read
    猜你喜欢
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 2016-10-04
    • 2019-09-12
    • 1970-01-01
    相关资源
    最近更新 更多