Index 的definition 是:
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。
在您的情况下,index 调用(可能是 &self.items[idx] btw)的 self 是 self.items,因此编译器认为返回值必须限制为从 self.items 借用,但items 归next 的self 所有,因此从self.items 借用是从self 本身借用。
也就是说,编译器只能保证index 的返回值在self 存在的时间内有效(以及关于变异的各种担忧),所以&mut self 的生命周期和返回的@987654341 @ 必须链接。
如果编译它,要查看错误,链接引用是编译器建议的:
<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 特征的签名更严格,因此是非法的。 (具有这种生命周期安排的迭代器可能很有用,但它们不适用于许多常见的消费者,例如.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")
}
}
}
这会存储两个内联的Ts(例如直接在堆栈上)并允许对它们进行索引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 绑定,可能是通过手动实现Clone 而不是derive,这样Stride 可以直接与&[T] 一起使用,即Stride::new(items: &I, ...) Stride::new(&[1, 2, 3], ...) 可以工作,而不必像默认的Sized 绑定要求那样拥有双层Stride::new(&&[1, 2, 3], ...)。)
playpen