实现一个迭代器,从另一个结构懒惰地获取数据

时间:2018-12-26 17:20:39

标签: rust iterator

我正在尝试对从本地磁盘延迟获取的数据编写迭代器:

struct Data {}

struct DataDecoder {}

impl DataDecoder {
    fn decode_data(&mut self) -> Option<Vec<Data>> {
        // in reality does some IO, might fail
        Some(vec![Data {}])
    }

    fn iter(&self) -> DataIterator {
        DataIterator {
            decoder: self,
            data: None,
            idx: 0,
        }
    }
}

struct DataIterator<'a> {
    decoder: &'a DataDecoder,
    data: Option<Vec<Data>>,
    idx: usize,
}

impl<'a> Iterator for DataIterator<'a> {
    type Item = &'a Data;

    fn next(&mut self) -> Option<Self::Item> {
        if self.data.is_none() {
            self.data = self.decoder.decode_data();
        }
        let ret = match self.data {
            None => None,
            Some(ref data) => data.get(self.idx),
        };
        self.idx += 1;
        ret
    }
}

我遇到编译错误:

error[E0495]: cannot infer an appropriate lifetime for pattern due to conflicting requirements
  --> src/lib.rs:35:18
   |
35 |             Some(ref data) => data.get(self.idx),
   |                  ^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 29:5...
  --> src/lib.rs:29:5
   |
29 | /     fn next(&mut self) -> Option<Self::Item> {
30 | |         if self.data.is_none() {
31 | |             self.data = self.decoder.decode_data();
32 | |         }
...  |
38 | |         ret
39 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/lib.rs:35:18
   |
35 |             Some(ref data) => data.get(self.idx),
   |                  ^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 26:6...
  --> src/lib.rs:26:6
   |
26 | impl<'a> Iterator for DataIterator<'a> {
   |      ^^
   = note: ...so that the types are compatible:
           expected std::iter::Iterator
              found std::iter::Iterator

我需要更改什么?

0 个答案:

没有答案