我知道Lifetime in Iterator impl,但我想了解更多的細節來幫助我正確理解。迭代器返回自己的引用
我想寫一個無限Iterator
,返回&[0]
,&[0, 1]
,&[0, 1, 2]
等。我想這樣寫:
struct Countings(Vec<usize>);
impl Countings {
fn new() -> Countings { Countings(vec![]) }
}
impl Iterator for Countings {
type Item = &[usize];
fn next(&mut self) -> Option<Self::Item> {
self.0.push(self.0.len());
Some(self.0.as_slice())
}
}
我不能因爲類型Countings::Item
沒有一輩子。
error[E0106]: missing lifetime specifier
--> src/lib.rs:8:17
|
8 | type Item = &[usize];
| ^expected lifetime parameter
所以我加一個。它必須受impl Iterator
的約束。這反過來需要在struct Countings
上有一個生命週期參數。到目前爲止,我在這裏:
struct Countings<'a>(Vec<usize>);
impl<'a> Countings<'a> {
fn new() -> Countings<'a> { Countings(vec![]) }
}
impl<'a> Iterator for Countings<'a> {
type Item = &'a [usize];
fn next(&mut self) -> Option<Self::Item> {
self.0.push(self.0.len());
Some(self.0.as_slice())
}
}
現在我有一個不同的錯誤:
error[E0392]: parameter `'a` is never used
--> src/lib.rs:1:18
|
1 | struct Countings<'a>(Vec<usize>);
| ^^
|
= help: consider removing `'a` or using a marker such as `std::marker::PhantomData`
我好好考慮一下:
use std::marker::PhantomData;
struct Countings<'a>(Vec<usize>, PhantomData<&'a [usize]>);
impl<'a> Countings<'a> {
fn new() -> Countings<'a> { Countings(vec![], PhantomData) }
}
impl<'a> Iterator for Countings<'a> {
type Item = &'a [usize];
fn next(&mut self) -> Option<Self::Item> {
self.0.push(self.0.len());
Some(self.0.as_slice())
}
}
但無濟於事:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src/lib.rs:14:25
|
14 | Some(self.0.as_slice())
| ^^^^^^^^
問題1:什麼是「衝突的要求s「嗎?
問題2:answer cited above表示Item
必須借用Iterator
包裝的東西。我已閱讀std::slice::Windows
的來源,這是一個很好的例子。然而,在我的情況下,我想要改變Vec
每次調用next()
。那可能嗎?
謝謝。你的答案有一些有用的東西。如果我能接受這兩個答案,但我認爲弗朗西斯的回答更好地集中在我的兩個問題上。 – apt1002