无法通过&mut Read

时间:2018-09-02 21:25:23

标签: rust

我有一个带有以下签名的函数:

fn f(input: &mut Read, output: &mut Write)

然后我尝试通过Vec<u8>作为输入和输出:

let mut in: Vec<u8> = Vec::new();
let mut out: Vec<u8> = Vec::new();
f(&mut in[..], &mut out);

使用out编译器似乎很好,但是我遇到关于in的错误:

error[E0277]: the trait bound `[u8]: std::io::Read` is not satisfied
--> src/crypto.rs:109:25
    |
109 |     f(&mut in[..], &mut out);     
            ^^^^^^^^^^^ the trait `std::io::Read` is not implemented for `[u8]`
    |
    = help: the following implementations were found:
              <&'a [u8] as std::io::Read>
    = note: required for the cast to the object type `std::io::Read`

error[E0277]: the trait bound `[u8]: std::marker::Sized` is not satisfied
--> src/crypto.rs:109:25
    |
109 |     f(&mut in[..], &mut out);
    |       ^^^^^^^^^^^ `[u8]` does not have a constant size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `[u8]`
    = note: required for the cast to the object type `std::io::Read`

将Vec传递到此类接口的正确方法是什么?

1 个答案:

答案 0 :(得分:3)

您的示例很容易解决,只需借用切片即可!

use std::io::{copy, Read, Write};

fn f(input: &mut Read, output: &mut Write) {
    copy(input, output).unwrap();
}

fn main() {
    let i = vec![0u8, 1, 2, 3];
    let mut o = Vec::new();
    f(&mut &i[..], &mut o);
    println!("{:?} {:?}", i, o);
}

尽管我不知道,为什么你要i[..],因为在这种特定情况下,读不会改变阅读器(请注意,它可以改变阅读器,因为它需要一个可变引用,它可以(例如在套接字上)消耗其读取的字节)。

您也可以只写

f(&mut i.as_slice(), &mut o);

如果您不被迫克隆vec。