延长变量的生命周期 [英] Extend lifetime of variable

查看:36
本文介绍了延长变量的生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的函数内部构建的向量中返回一个切片.显然这行不通,因为 v 的生命周期过早到期.我想知道是否有办法延长 v 的生命周期.我想返回一个普通的切片,而不是一个向量.

I'm trying to return a slice from a vector which is built inside my function. Obviously this doesn't work because v's lifetime expires too soon. I'm wondering if there's a way to extend v's lifetime. I want to return a plain slice, not a vector.

pub fn find<'a>(&'a self, name: &str) -> &'a[&'a Element] {
    let v: Vec<&'a Element> = self.iter_elements().filter(|&elem| elem.name.borrow().local_name == name).collect();
    v.as_slice()
}

推荐答案

你不能强行延长一个值的生命周期;你只需要返回完整的Vec.如果我问,为什么要返回切片本身?它几乎总是不必要的,因为 Vec 可以廉价地(在简单的语法和运行时的低开销的意义上)强制转换为切片.

You can't forcibly extend a value's lifetime; you just have to return the full Vec. If I may ask, why do you want to return the slice itself? It is almost always unnecessary, since a Vec can be cheaply (both in the sense of easy syntax and low-overhead at runtime) coerced to a slice.

或者,您可以返回迭代器:

Alternatively, you could return the iterator:

use std::iter;

pub fn find<'a>(&'a self, name: &str) -> Box<Iterator<Item = &'a Element> + 'a> {
    Box::new(self.iter_elements()
       .filter(move |&elem| elem.name.borrow().local_name == name))
}

现在,您将不得不使用迭代器特征对象,因为闭包具有不可命名的类型.

For now, you will have to use an iterator trait object, since closure have types that are unnameable.

注意.我不得不将 filter 闭包更改为 capture-by-move(move 关键字)以确保它可以返回,否则 name 变量将只是传递到 find 的堆栈帧中的闭包指针,因此将被限制离开 find.

NB. I had to change the filter closure to capture-by-move (the move keyword) to ensure that it can be returned, or else the name variable would just passed into the closure pointer into find's stack frame, and hence would be restricted from leaving find.

这篇关于延长变量的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆