我正尝试添加具有通用类型std::io::Cursor
的使用R
,但保留Read
类型限制,以便可以访问Read
特性并随后可以支持bytes()
方法。
到目前为止,这是我的结构定义:
struct Parse<'parse, R: Read + BufRead + 'parse> {
tokens: Vec<Token>,
source: Cursor<&'parse mut R>,
}
假设我有一个变量parser
,它是Parse
的实例,那么我希望能够调用parser.source.bytes()
。 bytes()
是Read
提供的一种方法。尽管R
周围有注解,但编译器告诉我R
不满足std::io::Read
特质范围。
以下是上下文中的代码段以及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() {
//...
}
生成以下错误消息:
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`
帮助表示感谢!
答案 0 :(得分:7)
检查错误消息后的注释:
= 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`
Read
implementation for Cursor<T>
仅在T: AsRef<[u8]>
时定义。如果添加该约束,则Read
实现将可用:
impl<'parse, R: AsRef<[u8]> + BufRead + 'parse> Parse <'parse, R> {
在该代码中您仍然会有一些其他错误。但这应该可以回答您的表面问题。