无法将trait边界添加到结构的成员

Tim*_*ara 3 generics traits rust

我试图添加std::io::Cursor泛型类型的使用R,但保留Read类型边界,以便Read可以访问特征,然后可以支持bytes()方法.

到目前为止,这是我的结构定义:

struct Parse<'parse, R: Read + BufRead + 'parse> {
    tokens: Vec<Token>,
    source: Cursor<&'parse mut R>,
}
Run Code Online (Sandbox Code Playgroud)

假设我有一个变量parser是一个实例Parse,我希望能够调用parser.source.bytes().bytes()是一种方法Read.尽管有注释R,编译器告诉我R不满足std::io::Read特征界限.

以下是上下文中的代码片段以及到操场直接链接:

// 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() {
    //...
}
Run Code Online (Sandbox Code Playgroud)

生成以下错误消息:

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`
Run Code Online (Sandbox Code Playgroud)

帮助赞赏!

Pet*_*all 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`
Run Code Online (Sandbox Code Playgroud)

Read实施Cursor<T>仅当定义T: AsRef<[u8]>.如果添加该约束,则Read实现将可用:

impl<'parse, R: AsRef<[u8]> + BufRead + 'parse> Parse <'parse, R> {
Run Code Online (Sandbox Code Playgroud)

您仍会在该代码中出现一些其他错误.但这应该回答你的表面问题.