延长变量的寿命 [英] Extend lifetime of variable

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

问题描述

我正在尝试从函数内部构建的向量中返回一个切片.显然,这是行不通的,因为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.

NB.我必须将filter闭包更改为移动捕获(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天全站免登陆