简体   繁体   English

允许参考寿命比关闭寿命更长

[英]Allowing reference lifetime to outlive a closure

I'm getting to grips with Rust by trying to implement a singly-linked list. 我试图通过尝试实现单链表来处理Rust。 Here are my data structures: 这是我的数据结构:

struct Linked<T> {
    head: Option<Box<Node<T>>>
}

struct Node<T> {
    data: T,
    next: Option<Box<Node<T>>>
}

Now, I'd like to add an iterator to this: 现在,我想为此添加一个迭代器:

struct LinkedIter<'a, T: 'a> {
    node: Option<&'a Node<T>>,
}

I've written a .iter() method for Linked<T> , which compiles and works fine. 我为Linked<T>编写了一个.iter()方法,编译并正常工作。

impl<T> Linked<T> {
    fn iter(&self) -> LinkedIter<T> {
        LinkedIter { node: match self.head {
                Some(ref node) => Some(&**node),
                None           => None
            }
        }
    }
}

Now, this match block is converting an Option<Box<Linked<T>>> to an Option<&Linked<T>> . 现在,此match块正在将Option<Box<Linked<T>>>转换为Option<&Linked<T>> This is exactly what the Option::map() method is for. 这正是Option::map()方法的用途。 So I reimplemented this method, using head.as_ref() instead of head to avoid taking ownership of the Option 's contents in the closure. 所以我重新实现了这个方法,使用head.as_ref()而不是head来避免在闭包中取得Option的内容的所有权。

impl<T> Linked<T> {
    fn iter(&self) -> LinkedIter<T> {
        LinkedIter { node:
            self.head.as_ref().map(|b: &Box<Node<T>>| &**b)
        }
    }
}

Unfortunately, the reference created in the closure cannot be allowed to outlive the closure, because it refers to something passed into the closure as a parameter. 不幸的是,闭包中创建的引用不能超过闭包,因为它引用了作为参数传递给闭包的东西。 The compiler complains (paraphrased a bit): 编译器抱怨(转述一下):

error: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements: 错误:由于需求冲突,无法推断借用表达式的适当生命周期:

first, the lifetime cannot outlive the anonymous lifetime #1 defined [in the closure] 首先,生命周期不能超过匿名生命#1定义[在关闭]

but, the lifetime must be valid for [the lifetime of the iter function] 但是,生命周期必须对[ iter函数的生命周期]有效

so that the [ node: ] expression is assignable 这样[ node: ]表达式是可分配的

How can I explain to the compiler that the reference will still be valid after the closure ends? 我怎样才能向编译器解释在闭包结束后引用仍然有效?

(Playground) (操场)

The idea is to inform the compiler that the reference you're taking in map() lives as long as the iterator. 我们的想法是通知编译器你在map()中使用的引用与迭代器一样长。 I got it working like that: 我得到它的工作:

impl<T> Linked<T> {
    fn iter<'a>(&'a self) -> LinkedIter<T> {
        LinkedIter { node:
            self.head.as_ref().map(|b: &'a Box<Node<T>>| &**b)
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM