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

标签 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))
        }
    }
}

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

最佳答案

definitionIndex是:

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 .

在你的例子中,selfindex电话(可能是 &self.items[idx] 顺便说一句)是 self.items , 所以编译器认为返回值必须限制为从 self.items 借用,但是items属于nextself , 所以借自 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。)

playpen

关于rust - 需要帮助理解迭代器的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27809095/

相关文章:

opengl - 使用 Rust 宏生成和编译着色器

rust - 拥有值的矛盾 "missing lifetime specifier"错误

javascript - JavaScript 应用程序拒绝向 Rust Rocket 服务器发出错误连接请求

rust - 类型不匹配,使用 lookup_host 时预期 () 找到结果

Rust FFI 和 CUDA C 性能差异

rust - 如何修复 "cannot move out of dereference of ` std::cell::Ref <'_, servo_url::ServoUrl>`“编译错误与闭包

types - 扩展库中的固有类型是不好的形式吗?

rust - `as` 表达式只能用于原始类型之间的转换,或者,如何将 +1 添加到泛型 T

rust - 如何将具有 2 个参数的函数作为参数传递给函数?

mysql - 柴油查询中的"SOUNDS LIKE"