【发布时间】:2017-03-20 06:04:35
【问题描述】:
我知道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:什么是“冲突要求”?
问题 2:answer cited above 表示 Item 必须借用 Iterator 包装的东西。我已经阅读了std::slice::Windows 的源代码,这是一个很好的例子。但是,在我的情况下,我想在每次调用 next() 时改变 Vec。这可能吗?
【问题讨论】: