需要帮助理解迭代器的生命周期

awe*_*kie 1 rust

考虑以下代码:

#[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))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当前出现错误,表明编译器无法推断该行的适当生命周期Some(self.items.index(&idx))。返回值的生命周期应该是多少?我相信它应该与 具有相同的生命周期self.items,因为Index特征方法返回一个与实现者具有相同生命周期的引用Index

huo*_*uon 5

定义是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;
}
Run Code Online (Sandbox Code Playgroud)

具体来说,index返回对元素的引用,其中该引用与 具有相同的生命周期self。也就是说,它借用了self

在您的情况下,self调用的index(可能是&self.items[idx]顺便说一句)是self.items,因此编译器认为返回值必须限制为借用self.items,但itemsnext's所有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;
          ...
Run Code Online (Sandbox Code Playgroud)

然而,建议的签名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")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这会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);
Run Code Online (Sandbox Code Playgroud)

倒数第二行很糟糕!它无效,value因为stride, 及其字段items(对)在内存中移动,因此内部的引用value指向移动的数据;这是非常不安全而且非常糟糕的。

建议的生命周期通过借用和禁止移动来阻止这个问题(以及其他几个有问题的问题)stride,但是,正如我们在上面看到的,我们不能使用它。

解决这个问题的一种技术是将存储元素的内存与迭代器本身分开,即将 的定义更改Stride为:

pub struct Stride<'a, I: Index<uint> + 'a> {
    items: &'a I,
    len: uint,
    current_idx: uint,
    stride: uint,
}
Run Code Online (Sandbox Code Playgroud)

(添加对 的引用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))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

(理论上,可以?Sized在其中添加一个边界,可能通过手动实现Clone而不是deriveing 它,以便Stride可以直接与 a 一起使用&[T],即可以工作,而不是必须像默认边界要求Stride::new(items: &I, ...) Stride::new(&[1, 2, 3], ...)那样具有双层。)Stride::new(&&[1, 2, 3], ...)Sized

婴儿围栏