如何在返回带有生命周期引用的结构的特征上实现Iterator?

时间:2018-10-30 20:53:51

标签: generics rust iterator traits

我正在编写一个Rust(1.30)库,该库具有引用字符串的结构。可以将它们编码为几种不同的文件格式。我想要一个通用的“读者”特征来读取结构并返回它们。我有这个。

use std::io::Read;

struct MyStruct<'a> {
    data: &'a str,
}

trait MyStructReader<R>
where
    R: Read,
{
    fn new(r: R) -> Self;
    fn into_inner(self) -> R;
    // ...
    fn next_obj<'a>(&'a mut self) -> Option<MyStruct<'a>>;
}

从逻辑上讲,我应该能够在MyStructReader上进行迭代(只需调用MyStructReader::next_object),但是我无法实现该实现:

有了这个,我得到这个错误

impl<R> Iterator for MyStructReader<R>
where
    R: Read,
{
    type Item = MyStruct<'a>;

    fn next<'a>(&'a mut self) -> Option<MyStruct<'a>> {
        self.next_obj()
    }
}
error[E0261]: use of undeclared lifetime name `'a`
  --> src/lib.rs:21:26
   |
21 |     type Item = MyStruct<'a>;
   |                          ^^ undeclared lifetime

如果我添加生命周期:

impl<'a, R> Iterator for MyStructReader<R>
where
    R: Read,
{
    type Item = MyStruct<'a>;

    fn next<'a>(&'a mut self) -> Option<MyStruct<'a>> {
        self.next_obj()
    }
}
error[E0496]: lifetime name `'a` shadows a lifetime name that is already in scope
  --> src/lib.rs:23:13
   |
17 | impl<'a, R> Iterator for MyStructReader<R>
   |      -- first declared here
...
23 |     fn next<'a>(&'a mut self) -> Option<MyStruct<'a>> {
   |             ^^ lifetime 'a already in scope

我该怎么做? Rust playground

0 个答案:

没有答案