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

时间:2017-06-08 14:09:13

标签: rust

我正在尝试将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>`

1 个答案:

答案 0 :(得分:5)

你做不到。检查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实现{{ 3}}:

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