考虑以下代码:
#[derive(Clone)]
pub struct Stride<'a, I: Index<uint> + 'a> {
items: I,
len: uint,
current_idx: uint,
stride: uint,
}
impl<'a, I> Iterator for Stride<'a, I> where I: Index<uint> {
type Item = &'a <I as Index<uint>>::Output;
#[inline]
fn next(&mut self) -> Option<&'a <I as Index<uint>>::Output> {
if (self.current_idx >= self.len) {
None
} else {
let idx = self.current_idx;
self.current_idx += self.stride;
Some(self.items.index(&idx))
}
}
}
这目前是错误的,表示编译器无法为 Some(self.items.index(&idx))
行推断出合适的生命周期。返回值的生命周期应该是多少?我认为它应该与 self.items
具有相同的生命周期,因为 Index
特征方法返回一个与 Index
实现者具有相同生命周期的引用.
最佳答案
definition的 Index
是:
pub trait Index<Index: ?Sized> {
type Output: ?Sized;
/// The method for the indexing (`Foo[Bar]`) operation
fn index<'a>(&'a self, index: &Index) -> &'a Self::Output;
}
具体来说,index
返回对元素的引用,其中该引用的生命周期与 self
相同.即借用self
.
在你的例子中,self
的 index
电话(可能是 &self.items[idx]
顺便说一句)是 self.items
, 所以编译器认为返回值必须限制为从 self.items
借用,但是items
属于next
的 self
, 所以借自 self.items
是从 self
借来的本身。
也就是说编译器只能保证index
的返回值有效期为 self
生命(以及对突变的各种担忧),因此 &mut self
的生命周期和返回的 &...
必须链接。
如果编译它,看到错误,链接引用是编译器的建议:
<anon>:23:29: 23:40 error: cannot infer an appropriate lifetime for autoref due to conflicting requirements
<anon>:23 Some(self.items.index(&idx))
^~~~~~~~~~~
<anon>:17:5: 25:6 help: consider using an explicit lifetime parameter as shown: fn next(&'a mut self) -> Option<&'a <I as Index<uint>>::Output>
<anon>:17 fn next(&mut self) -> Option<&'a <I as Index<uint>>::Output> {
<anon>:18 if (self.current_idx >= self.len) {
<anon>:19 None
<anon>:20 } else {
<anon>:21 let idx = self.current_idx;
<anon>:22 self.current_idx += self.stride;
...
不过,建议签名fn next(&'a mut self) -> Option<&'a <I as Index<uint>>::Output>
比 Iterator
的签名更严格trait,所以是非法的。 (具有这种生命周期安排的迭代器可能很有用,但它们不适用于许多普通消费者,例如 .collect
。)
编译器正在防止的问题由如下类型证明:
struct IndexablePair<T> {
x: T, y: T
}
impl Index<uint> for IndexablePair<T> {
type Output = T;
fn index(&self, index: &uint) -> &T {
match *index {
0 => &self.x,
1 => &self.y,
_ => panic!("out of bounds")
}
}
}
这存储了两个 T
s 内联(例如直接在堆栈上)并允许索引它们 pair[0]
和 pair[1]
. index
方法返回一个直接指向该内存(例如堆栈)的指针,因此如果 IndexablePair
值在内存中移动,那些指针将变得无效,例如(假设 Stride::new(items: I, len: uint, stride: uint)
):
let pair = IndexablePair { x: "foo".to_string(), y: "bar".to_string() };
let mut stride = Stride::new(pair, 2, 1);
let value = stride.next();
// allocate some memory and move stride into, changing its address
let mut moved = box stride;
println!("value is {}", value);
倒数第二行很糟糕!它使 value
无效因为stride
, 它是字段 items
(这对)在内存中移动,所以里面的引用 value
然后指向移动的数据;这是非常不安全和非常糟糕的。
建议的生命周期通过借用 stride
来解决这个问题(以及其他几个有问题的问题)并禁止移动,但是,正如我们在上面看到的那样,我们不能使用它。
解决这个问题的技术是将存储元素的内存与迭代器本身分开,即更改 Stride
的定义到:
pub struct Stride<'a, I: Index<uint> + 'a> {
items: &'a I,
len: uint,
current_idx: uint,
stride: uint,
}
(添加对 items
的引用。)
然后编译器保证存储元素的内存独立于Stride
。值(也就是说,在内存中移动 Stride
不会使旧元素无效)因为有一个非拥有指针将它们分开。这个版本编译得很好:
use std::ops::Index;
#[derive(Clone)]
pub struct Stride<'a, I: Index<uint> + 'a> {
items: &'a I,
len: uint,
current_idx: uint,
stride: uint,
}
impl<'a, I> Iterator for Stride<'a, I> where I: Index<uint> {
type Item = &'a <I as Index<uint>>::Output;
#[inline]
fn next(&mut self) -> Option<&'a <I as Index<uint>>::Output> {
if (self.current_idx >= self.len) {
None
} else {
let idx = self.current_idx;
self.current_idx += self.stride;
Some(self.items.index(&idx))
}
}
}
(理论上可以在其中添加一个 ?Sized
绑定(bind),可能是通过手动实现 Clone
而不是 derive
,这样 Stride
可以直接与 &[T]
一起使用,即 Stride::new(items: &I, ...)
Stride::new(&[1, 2, 3], ...)
会起作用,而不是像默认的 Stride::new(&&[1, 2, 3], ...)
绑定(bind)要求的那样必须有双层 Sized
。)
关于rust - 需要帮助理解迭代器的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27809095/