rust - 无法通过 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 传递到此类接口的正确方法是什么?
解决方案
您的示例很容易解决,只需借用切片!
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。
推荐阅读
- php - 如何从 PHP 中的类别/子类别数组中获取常见的子类别?
- asp.net-core - 添加 Swashbuckle 备注时如何获取 JSON 格式?
- java - 检查字符串是否包含特定字符的最有效方法
- ubuntu - dpkg-buildpackage 未满足的构建依赖项
- kubernetes - 是否可以在 Azure Kubernetes 服务等托管 Kubernetes 集群上应用和维护 CIS 基准合规性?
- arrays - Powershell 获取内容 + 数组
- c# - XAML 将列表转换为控件列表
- single-sign-on - Pingfederate kerberos 身份验证正在对来自任何域的任何用户进行身份验证
- c# - 如何查询 UWP 应用程序中的特定列?
- c++ - 使用佳能 EDSDK 时出现未定义的引用错误