无法将 Vec<u8> 传递给需要 &mut Read 的函数

3
我有一个函数,其签名如下:

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传递到此接口的正确方法?

@Hellseher 刚刚尝试了一下 - 它不接受迭代器,而是需要一个 &[u8] 用于转换为 Read。 - undefined
下次请尽量创建一个MCVE。这将有助于您和我们更轻松地解决问题。 - undefined
in 是一个保留关键字,不能用作变量名。 - undefined
1个回答

4

您的例子相当容易解决,只需借用切片即可!

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[..],因为在这种特定情况下,read不会改变读取器(请注意它可以改变读取器,因为它需要可变引用,可以(例如在套接字上)消耗它读取的字节)。

你也可以只写

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

如果你不必克隆 vec。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接