[英]Unable to add trait bounds to member of a struct
I'm attempting to add use std::io::Cursor
with a generic type R
, but retain the Read
type bounds so that Read
trait is accessible, and subsequently can support bytes()
method. 我正在尝试使用泛型类型R
添加使用std::io::Cursor
,但保留Read
类型的边界以便可以访问Read
trait,并且随后可以支持bytes()
方法。
Here is my struct definition so far: 到目前为止,这是我的结构定义:
struct Parse<'parse, R: Read + BufRead + 'parse> {
tokens: Vec<Token>,
source: Cursor<&'parse mut R>,
}
Assuming I have a variable parser
that's an instance of Parse
, I want to be able to call parser.source.bytes()
. 假设我有一个变量parser
,它是Parse
的一个实例,我希望能够调用parser.source.bytes()
。 bytes()
is a method provided by Read
. bytes()
是Read
提供的方法。 Despite the annotation around R
, the compiler is telling me that R
isn't satisfying the std::io::Read
trait bounds. 尽管R
周围有注释,编译器告诉我R
不满足std::io::Read
特性边界。
Here is that snippet of code in context along with a direct link to the playground : 以下是上下文中的代码片段以及到操场的直接链接 :
// using Cursor because it tracks position internally
use std::io::{Cursor, Read, BufRead};
struct Token {
start: usize,
end: usize,
}
struct Parse<'parse, R: Read + BufRead + 'parse> {
tokens: Vec<Token>,
source: Cursor<&'parse mut R>,
}
impl<'parse, R: Read + BufRead + 'parse> Parse <'parse, R> {
fn new(source: &'parse mut R) -> Self {
Parse {
tokens: vec!(),
source: Cursor::new(source),
}
}
fn parse_primitive(&mut self) -> std::io::Result<Token> {
let start = self.source.position();
let bytes = self.source.bytes(); // <- error raised here
// dummy work
for _ in 0..3 {
let byte = bytes.next().unwrap().unwrap()
}
let end = self.source.position();
Ok(Token { start: start as usize, end: end as usize})
}
}
fn main() {
//...
}
Generates the following error message: 生成以下错误消息:
error[E0599]: no method named `bytes` found for type `std::io::Cursor<&'parse mut R>` in the current scope
--> src/main.rs:24:33
|
24 | let bytes = self.source.bytes();
| ^^^^^
|
= note: the method `bytes` exists but the following trait bounds were not satisfied:
`std::io::Cursor<&mut R> : std::io::Read`
`&mut std::io::Cursor<&'parse mut R> : std::io::Read`
Help appreciated! 帮助赞赏!
Check the notes after the error messages: 检查错误消息后的注释:
= note: the method `bytes` exists but the following trait bounds were not satisfied:
`std::io::Cursor<&mut R> : std::io::Read`
`&mut std::io::Cursor<&'parse mut R> : std::io::Read`
The Read
implementation for Cursor<T>
is only defined when T: AsRef<[u8]>
. Cursor<T>
的Read
实现仅在T: AsRef<[u8]>
时定义。 If you add that constraint then the Read
implementation will be available: 如果添加该约束,则Read
实现将可用:
impl<'parse, R: AsRef<[u8]> + BufRead + 'parse> Parse <'parse, R> {
You will still have a few other errors in that code. 您仍会在该代码中出现一些其他错误。 But this should answer your surface question. 但这应该回答你的表面问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.