簡體   English   中英

從Iterator實現調用方法時,無法推斷autoref的適當生命周期

[英]Cannot infer appropriate lifetime for autoref when calling a method from an Iterator implementation

我正在嘗試為一個結構實現Iterator特性,該結構充當i32值數組的i32 ,但我一直在編譯器中抱怨無法在下一個方法中推斷出生命周期。

我知道需要幫助理解迭代器的生命周期 ,但是因為我的結構只是借用了數組的一部分,所以我將實際元素的內存與我的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)
   |         ^^^^^^^^^^^^^

您需要更新get方法以返回具有更長壽命的引用:

// Use 'a from impl<'a> IntegerArrayBag<'a>
fn get(&self, idx: usize) -> Option<&'a i32> {

然后它將編譯。

更改get(…)以返回Option<&'a i32>使其編譯。

游樂場網址: https//play.rust-lang.org/?gist = 10783e90287b7111c126&version =stable

要點網址: https//gist.github.com/10783e90287b7111c126

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM