首页 文章

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

提问于
浏览
3

我正在尝试使用通用类型 R 添加使用 std::io::Cursor ,但保留 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`

帮助赞赏!

1 回答

  • 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> {
    

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

相关问题