我有一个具有以下签名的函数:
fn f(input: &mut Read, output: &mut Write)
我尝试将Vec<u8>
s作为输入和输出传递:
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传递到这样的界面的正确方法是什么?
你的例子很容易解决,只需借用切片!
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。