从Iterator实现调用方法时无法推断自动引用的适当生命周期

7
我正在尝试为一个结构体实现Iterator特质,该结构体作为i32值数组的借用者,但我一直遇到编译器抱怨无法推断next方法内的生命周期的问题。
我知道需要帮助理解迭代器生命周期,但由于我的结构体只是借用了数组的一个切片,我将实际元素的内存与我的IntegerArrayBag分开。
#[derive(Debug)]
struct IntegerArrayBag<'a> {
    arr: &'a [i32],
    idx: usize,
}

impl<'a> IntegerArrayBag<'a> {
    fn len(&self) -> usize {
        self.arr.len()
    }

    fn get(&self, idx: usize) -> Option<&i32> {
        if self.arr.len() > idx {
            Some(&self.arr[idx])
        } else {
            None
        }
    }
}

impl<'a> Iterator for IntegerArrayBag<'a> {
    type Item = &'a i32;

    fn next(&mut self) -> Option<&'a i32> {
        let idx = self.idx;
        self.idx += 1;
        self.get(idx)
    }
}

如果尝试编译这段代码,编译器会报错:

error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
  --> src/main.rs:27:14
   |
27 |         self.get(idx)
   |              ^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 24:5...
  --> src/main.rs:24:5
   |
24 | /     fn next(&mut self) -> Option<&'a i32> {
25 | |         let idx = self.idx;
26 | |         self.idx += 1;
27 | |         self.get(idx)
28 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:27:9
   |
27 |         self.get(idx)
   |         ^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 21:1...
  --> src/main.rs:21:1
   |
21 | / impl<'a> Iterator for IntegerArrayBag<'a> {
22 | |     type Item = &'a i32;
23 | |
24 | |     fn next(&mut self) -> Option<&'a i32> {
...  |
28 | |     }
29 | | }
   | |_^
note: ...so that expression is assignable (expected std::option::Option<&'a i32>, found std::option::Option<&i32>)
  --> src/main.rs:27:9
   |
27 |         self.get(idx)
   |         ^^^^^^^^^^^^^
2个回答

6
您需要更新您的get方法,以返回具有更长生命周期的引用:
// Use 'a from impl<'a> IntegerArrayBag<'a>
fn get(&self, idx: usize) -> Option<&'a i32> {

然后它将会编译。


当然。它是独立的,所以我也必须这样声明它。谢谢。 - jtepe

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接