rust - 返回对内部集合的引用时的迭代器生命周期问题

标签 rust reference iterator lifetime

我有一个结构,可以将数据延迟加载到内部向量中(但对于示例,这是省略的)。然后我正在实现 IntoIteratorIterator对于 IntoIterator 类型:

struct EntryOwned(u32);
struct Entry<'a>(&'a u32);

impl<'a> EntryOwned {
    fn to_entry(&'a self) -> Entry<'a> {
        Entry(&self.0)
    }
}

struct LazyStruct {
    cache: Vec<EntryOwned>,
}

impl<'a> LazyStruct {
    fn new(data: Vec<EntryOwned>) -> LazyStruct {
        Self {
            cache: data,
        }
    }

    fn get_entry(&'a self, index: usize) -> Option<Entry<'a>> {
        match self.cache.get(index) {
            Some(entry_owned) => Some(entry_owned.to_entry()),
            None => None,
        }
    }
}

impl<'a> IntoIterator for &'a mut LazyStruct {
    type Item = Entry<'a>;
    type IntoIter = LazyStructIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        LazyStructIter {
            inner: self,
            current_index: 0,
        }
    }
}

struct LazyStructIter<'a> {
    inner: &'a mut LazyStruct,
    current_index: usize,
}

impl<'a> LazyStructIter<'a> {
    fn next_item(&'a mut self) -> Option<Entry<'a>> {
        if self.current_index > self.inner.cache.len() {
            return None;
        }
        let ret = self.inner.get_entry(self.current_index);
        self.current_index += 1;
        ret
    }
}

impl<'a> Iterator for LazyStructIter<'a> {
    type Item = Entry<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        self.next_item()
    }
}

这让我想到了一个终生的问题:
   Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
  --> src/main.rs:64:14
   |
64 |         self.next_item()
   |              ^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 63:5...
  --> src/main.rs:63:5
   |
63 | /     fn next(&mut self) -> Option<Self::Item> {
64 | |         self.next_item()
65 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:64:9
   |
64 |         self.next_item()
   |         ^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 60:6...
  --> src/main.rs:60:6
   |
60 | impl<'a> Iterator for LazyStructIter<'a> {
   |      ^^
note: ...so that the types are compatible
  --> src/main.rs:64:14
   |
64 |         self.next_item()
   |              ^^^^^^^^^
   = note: expected  `&mut LazyStructIter<'_>`
              found  `&mut LazyStructIter<'a>`

引用的生命周期应该绑定(bind)到 LazyStruct ,但我不能改变 Iter 特征不接受任何生命周期说明符。
我已经检查了类似问题的一些答案:
Iterator returning items by reference, lifetime issue
How do I write an iterator that returns references to itself?

编辑 : Entry是更复杂的数据结构,无法复制。我必须将它绑定(bind)到特定的生命周期,因为它包含对事物的引用。

其中之一指出迭代器应该持有对原始集合的引用而不是拥有它,因为它不允许返回具有自身生命周期的引用。但我无法让它工作。
那么,我应该如何在这里播放引用资料?

这里是 playground example

任何帮助都非常受欢迎,提前谢谢大家!

最佳答案

你不能。

您要求 next() 返回的每件商品有一个与生命周期相关的引用LazyStructIter 的存在迭代器。
Iterator 无法做到这一点界面:

pub trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;

但是有可能将特征定义为:
trait FakeIterator<'a> {
    type Item;

    fn next(&'a mut self) -> std::option::Option<Self::Item>;
}

impl<'a> FakeIterator<'a> for LazyStructIter<'a> {
    type Item = Entry<'a>;

    fn next(&'a mut self) -> Option<Self::Item> {
        self.next_item()
    }
}

拥有一种返回从自身借用的项目的迭代器的能力是
RFC 1598 - GAT .

另请参阅 article有关此主题的解决方法的集合。

关于rust - 返回对内部集合的引用时的迭代器生命周期问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60788168/

相关文章:

c++ - 我怎样才能将 std::map 的迭代器递减一定数量?

c++ - 将 const 容器引用作为参数传递时如何逃脱 const_iterator 陷阱

unit-testing - 在宏上下文测试中使用 panic::catch_unwind 以解决单元测试中的 panic 问题

rust - 将 `use` 声明放入 Rust 的推荐位置在哪里?

javascript "this"再次指向 Window 对象

rust - 如何编写不拥有(或不消耗)迭代器所有权的函数? [复制]

rust - 如何获取模块树?

Rust:无法访问子目录中的函数

c++ - constexpr int* ptr =&i 在 msvc 中编译但不使用 clang 和 gcc

swift - 如何使放在 RunLoop 上的计时器失效