首页 > 解决方案 > 无法通过 Vec变成一个函数,取 &mut 读取

问题描述

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

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

标签: rust

解决方案


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

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

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

你也可以写

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

如果您没有被迫克隆 vec。


推荐阅读