gpt4 book ai didi

rust - 如何从 std::io::Bytes 转换为 &[u8]

转载 作者:行者123 更新时间:2023-11-29 07:58:07 29 4
gpt4 key购买 nike

我正在尝试将 HTTP 响应的内容写入文件。

extern crate reqwest;

use std::io::Write;
use std::fs::File;

fn main() {
let mut resp = reqwest::get("https://www.rust-lang.org").unwrap();
assert!(resp.status().is_success());

// Write contents to disk.
let mut f = File::create("download_file").expect("Unable to create file");
f.write_all(resp.bytes());
}

但是我得到以下编译错误:

error[E0308]: mismatched types
--> src/main.rs:12:17
|
12 | f.write_all(resp.bytes());
| ^^^^^^^^^^^^ expected &[u8], found struct `std::io::Bytes`
|
= note: expected type `&[u8]`
found type `std::io::Bytes<reqwest::Response>`

最佳答案

你不能。检查the docs for io::Bytes , 没有合适的方法。这是因为 io::Bytes 是一个逐字节返回内容的迭代器,因此甚至可能 没有一个底层数据片。

如果你只有io::Bytes,你需要collect将迭代器转换为 Vec:

let data: Result<Vec<_>, _> = resp.bytes().collect();
let data = data.expect("Unable to read data");
f.write_all(&data).expect("Unable to write data");

但是,在大多数情况下,您可以访问实现Read 的类型,因此您可以改为使用Read::read_to_end。 :

let mut data = Vec::new();
resp.read_to_end(&mut data).expect("Unable to read data");
f.write_all(&data).expect("Unable to write data");

在这种特定情况下,您可以使用 io::copy直接从 Request 复制到文件,因为 Request 实现了 io::ReadFile 实现了 io::Write :

extern crate reqwest;

use std::io;
use std::fs::File;

fn main() {
let mut resp = reqwest::get("https://www.rust-lang.org").unwrap();
assert!(resp.status().is_success());

// Write contents to disk.
let mut f = File::create("download_file").expect("Unable to create file");
io::copy(&mut resp, &mut f).expect("Unable to copy data");
}

关于rust - 如何从 std::io::Bytes 转换为 &[u8],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44438059/

29 4 0