[英]Implementing Read trait : trait bound `std::error::Error + 'static: std::marker::Sized` is not satisfied
I want to implement the Read
trait for a struct for the purpose of using it in a BufReader
to pass to a library. 我想实现结构的Read
特质,以便在BufReader
中使用它传递给库。 The library uses a BufReader
as input because it should work with Stdin
and with an in-memory object that implements Read
. 该库使用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 ) ( 游乐场 )
When trying to implement Read
for the struct, I get the error: 尝试为结构实现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`
I built the library myself, so it could be changed but it works very well with Stdin
and I now want to use it with a struct. 我自己构建了库,因此可以对其进行更改,但它可以与Stdin
一起Stdin
,现在我想将其与结构一起使用。 The library uses BufReader::lines
, so it could be exchanged with an iterator, but as I understood, this would break compatibility with Stdin
, as I was only able to build a BufReader
around Stdin
, not an iterator. 该库使用BufReader::lines
,因此可以与迭代器进行交换,但是据我Stdin
,这将破坏与Stdin
兼容性,因为我只能围绕Stdin
而不是迭代器构建BufReader
。
How do I resolve this error? 如何解决此错误? What error object has a constant size known at compile-time? 哪个错误对象在编译时已知大小恒定?
Return 返回
Result<usize, std::io::Error>
Instead of 代替
Result<usize, Error>
std::error::Error
, which you're using in your signature, is a trait. 您在签名中使用的std::error::Error
是一个特征。 You can't return a trait directly. 您不能直接返回特征。
You could also do 你也可以
Result<usize, Box<dyn Error>>
A “trait object”, but I don't see why you would in this case. 一个“特质对象”,但我不明白为什么在这种情况下您会这么做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.