rust - 文件结构不被视为实现读取?

标签 rust traits

我正在制作一个特征,它将从各种文件格式中读取/解码为特定对象。该特征有一个通用的 std::io::Read 类用于内部读取器对象。我正在尝试制作一个方便的 from_filename 构造函数,它将打开文件并使用它。但是我似乎无法让它工作。

这是代码:

use std::io::Read;
use std::fs;
use std::path::Path;

trait MyObjectReader {
    type R: Read;

    fn new(Self::R) -> Self;

    fn from_filename(filename: &str) -> Self where Self: Sized {
        let open_file = fs::File::open(&Path::new(filename)).unwrap();
        Self::new(open_file)
    }

    // other methods will go here
}

然后我得到这个错误:

rustc 1.15.1 (021bd294c 2017-02-08)
error[E0308]: mismatched types
  --> <anon>:14:19
   |
14 |         Self::new(open_file)
   |                   ^^^^^^^^^ expected associated type, found struct `std::fs::File`
   |
   = note: expected type `<Self as MyObjectReader>::R`
   = note:    found type `std::fs::File`

我知道 .unwrap() 在库中低于标准,我稍后会更改。

我无法理解这个错误,因为 std::fs::File 没有实现 std::io::Read 吗?在我看来它应该有效。

最佳答案

doesn't std::fs::File implement std::io::Read?

是的。但是考虑一下你的特征的实现:

impl MyObjectReader for SomeReaderImpl {
    type R = AnythingYouLike;
    // .. etc
}

问题是 R 可能File,但也可能不是。

您的默认实现假设 RFile,因此也许该实现应该在 R 的特定实例中进行肯定是 文件:

use std::io::Read;
use std::fs;

trait MyObjectReader {
    type R: Read;

    fn new(Self::R) -> Self;

    fn from_filename(filename: &str) -> Self where Self: Sized;
}

struct MyFileReader;

impl MyObjectReader for MyFileReader {
    type R = fs::File;

    fn new(_: Self::R) -> Self {
        MyFileReader
    }

    fn from_filename(filename: &str) -> Self
        where Self: Sized
    {
        let open_file = fs::File::open(filename).unwrap();
        Self::new(open_file)
    }
}

关于rust - 文件结构不被视为实现读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42735664/

相关文章:

rust - 使用Box对结构进行反序列化

rust - 是否可能有多个段具有尖括号参数的类型路径?

scala - 使用密封特征作为 map 的键

function - 如何编写带迭代器的 Rust 函数?

rust - 是否有从 stdin 或 rust 文件中读取的特征?

rust - 如何从 std::string::String 获取 bytes::bytes::Bytes?

python - 矩阵中单元格之间连接的交互式可视化

oop - 当特征需要的状态多于结构中包含的状态时,如何为结构实现特征?

scala - 特征中未实现方法的返回类型

rust - 如何为 `IntoIter` 绑定(bind) `<&Self as IntoIterator>` 类型?