【问题标题】:Implementing Read trait : trait bound `std::error::Error + 'static: std::marker::Sized` is not satisfied实现读取特征:特征绑定`std::error::Error + 'static: std::marker::Sized`不满足
【发布时间】:2018-12-29 11:25:25
【问题描述】:

我想为结构实现Read 特征,以便在BufReader 中使用它以传递给库。该库使用BufReader 作为输入,因为它应该与Stdin 和实现Read 的内存对象一起使用。

use std::error::Error;
use std::io::Read;

pub struct Test {
    counter: u8,
}

impl Test {
    pub fn new() -> Test {
        Test { counter: 0 }
    }
}

impl Iterator for Test {
    type Item = String;

    fn next(&mut self) -> Option<Self::Item> {
        if self.counter < 2 {
            self.counter += 1;
            return Some("String".to_string());
        }

        None
    }
}

impl Read for Test {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
        let content = self.next();
        match content {
            None => Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                "End of Iterator",
            )),
            Some(string) => {
                let mut i = 0;
                loop {
                    if i >= buf.len() || i >= string.len() {
                        break;
                    }

                    buf[i] = string[i];
                    i += 1;
                }

                Ok(i)
            }
        }
    }
}

fn main() {
    let test = Test::new();
    let reader = std::io::BufReader::new(test);
    // let filter = lib_that_uses_bufreader::useful_function(reader);
}

(playground)

当尝试为结构实现Read 时,我收到错误:

error[E0277]: the trait bound `std::error::Error + 'static: std::marker::Sized` is not satisfied
  --> src/main.rs:28:5
   |
28 | /     fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
29 | |         let content = self.next();
30 | |         match content {
31 | |             None => Err(std::io::Error::new(
...  |
48 | |         }
49 | |     }
   | |_____^ `std::error::Error + 'static` does not have a constant size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `std::error::Error + 'static`
   = note: required by `std::result::Result`

我自己构建了这个库,因此可以对其进行更改,但它与Stdin 一起工作得很好,我现在想将它与结构一起使用。该库使用BufReader::lines,因此可以与迭代器交换,但据我了解,这会破坏与Stdin 的兼容性,因为我只能在Stdin 周围构建BufReader,而不是迭代器。

如何解决此错误?哪个错误对象具有在编译时已知的恒定大小?

【问题讨论】:

    标签: rust


    【解决方案1】:

    返回

    Result<usize, std::io::Error>
    

    代替

    Result<usize, Error>
    

    您在签名中使用的std::error::Error 是一个特征。你不能直接返回一个特征。

    你也可以

    Result<usize, Box<dyn Error>>
    

    一个“特征对象”,但我不明白你为什么会在这种情况下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      相关资源
      最近更新 更多