我正在尝试添加使用 std::io::Cursor
和通用类型 R
,但保留 Read
类型边界使得 Read
trait 是可访问的,随后可以支持 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`
感谢帮助!
最佳答案
检查错误信息后的注释:
= 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> {
您在该代码中仍然会有一些其他错误。但这应该可以回答您的表面问题。
关于generics - 无法将特征边界添加到结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51263244/