io - 如何从 Vec 或 Slice 读取 (std::io::Read)?

标签 io rust traits

Vec 支持 std::io::Write,因此可以编写带有 FileVec< 的代码,例如。从 API 引用来看,Vec 和切片都不支持 std::io::Read

有没有方便的方法来实现这个?是否需要编写包装器结构?

这是一个工作代码示例,它读取和写入一个文件,其中一行注释应该读取一个向量。

use ::std::io;

// Generic IO
fn write_4_bytes<W>(mut file: W) -> Result<usize, io::Error>
    where W: io::Write,
{
    let len = file.write(b"1234")?;
    Ok(len)
}

fn read_4_bytes<R>(mut file: R) -> Result<[u8; 4], io::Error>
    where R: io::Read,
{
    let mut buf: [u8; 4] = [0; 4];
    file.read(&mut buf)?;
    Ok(buf)
}

// Type specific

fn write_read_vec() {
    let mut vec_as_file: Vec<u8> = Vec::new();

    {   // Write
        println!("Writing Vec... {}", write_4_bytes(&mut vec_as_file).unwrap());
    }

    {   // Read
//      println!("Reading File... {:?}", read_4_bytes(&vec_as_file).unwrap());
        //                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        //                               Comment this line above to avoid an error!
    }
}

fn write_read_file() {
    let filepath = "temp.txt";
    {   // Write
        let mut file_as_file = ::std::fs::File::create(filepath).expect("open failed");
        println!("Writing File... {}", write_4_bytes(&mut file_as_file).unwrap());
    }

    {   // Read
        let mut file_as_file = ::std::fs::File::open(filepath).expect("open failed");
        println!("Reading File... {:?}", read_4_bytes(&mut file_as_file).unwrap());
    }
}

fn main() {
    write_read_vec();
    write_read_file();
}

失败并出现错误:

error[E0277]: the trait bound `std::vec::Vec<u8>: std::io::Read` is not satisfied
  --> src/main.rs:29:42
   |
29 |         println!("Reading File... {:?}", read_4_bytes(&vec_as_file).unwrap());
   |                                          ^^^^^^^^^^^^ the trait `std::io::Read` is not implemented for `std::vec::Vec<u8>`
   |
   = note: required by `read_4_bytes`

我想为文件格式编码器/解码器编写测试,而不必写入文件系统。

最佳答案

虽然向量不支持 std::io::Read , 切片做。

Rust 能够强制转换 Vec 导致这里有些困惑。在某些情况下会变成切片,但在其他情况下不会。

在这种情况下,需要对切片进行显式强制转换,因为在应用强制转换阶段,编译器不知道 Vec<u8> 没有实现Read .


当使用以下方法之一将向量强制转换为切片时,问题中的代码将起作用:

  • read_4_bytes(&*vec_as_file)
  • read_4_bytes(&vec_as_file[..])
  • read_4_bytes(vec_as_file.as_slice()) .

注意:

  • 最初问这个问题时,我正在服用 &Read而不是 Read .这使得传递对切片的引用失败,除非我传入 &&*vec_as_file我没想到会这样做。
  • 您还可以使用最新版本的 Rust as_slice()将 Vec 转换为切片。
  • 感谢@arete #rust寻找解决方案!

关于io - 如何从 Vec 或 Slice 读取 (std::io::Read)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42240663/

相关文章:

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

rust - 使用 Rust 动态库中的损坏的 Rust 函数

http - 如何在没有 HTTP 库的情况下发送 404 HTTP 响应?

generics - 从和进入实现

java - 如何在 java 文本文件中追加现有行

Haskell IO 与 Websockets

generics - 在 Rust 中一般乘以不同类型的值

scala - Scala 的 "type"关键字是什么意思?

variables - 使用 Haskell 从 if 语句获取输入并传递变量

rust - 将嵌套结构字段路径作为宏参数传递