如何解决“借入时的暂时价值下降"? [英] How to solve "temporary value dropped while borrowed"

查看:39
本文介绍了如何解决“借入时的暂时价值下降"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Rust(来自Javascript),并在Rust中尝试创建基于组件的UI模板.这是最小的示例我可以在Rust操场上繁殖.

I'm learning Rust (coming from Javascript), and in Rust I'm trying to create a component-based UI template. This is the minimum example I can reproduce in a Rust playground.

我有一个枚举向量.我想添加将返回一组新向量的组件.该组件从不是引用的成员函数返回向量.

I have a Vector of Enums. I want to add components that will return a new set of vectors. The component returns a vector from a member function that is not a reference.

let _new_children = match new_view.unwrap() {
    View::View(children) => children, // reference &Vec<View>
    View::Render(ref component) => component.render(), // struct Vec<View>
};

let _new_children = match new_view.unwrap() {
    View::View(children) => children,
    View::Render(ref component) => &component.render(), //  temporary value dropped while borrowed
};

我该如何解决这个问题?我是否需要重写函数检查两个向量之间差异的方式( itertools 具有zip_longest方法,我也使用该方法).

How can I solve this problem? Do I need to rewrite the way functions check the difference between two vectors (itertools has a zip_longest method, which I also use).

推荐答案

要返回对临时文件的引用,您需要使临时文件的生存期长于使用该引用的时间.

In order to return a reference to a temporary you need to make the temporary live longer than the use of that reference.

在您的代码中,匹配分支结束后,临时对象将被删除,因此对其的引用无法转义匹配.

In your code the temporary object is dropped as soon as the match branch ends, so a reference to it cannot escape the match.

Rust中有一个很好的技巧,可以延长临时文件的寿命.它包括在较大的块中声明您希望其驻留的临时名称+,而无需初始化 .然后,在实际创建临时对象的位置对其进行赋值初始化.像这样:

There is a nice trick in Rust to extend the lifetime of a temporary. It consist in declaring the temporary name+ in the larger block where you want it to live, without initializing it. Then you assign-initialize it where the object temporary is actually created. Something like this:

    let tmp_new;
    let new_children = match new_view.unwrap() {
        View::View(children) => children,
        View::Render(ref component) => {
            tmp_new = component.render();
            &tmp_new }
    };

现在 new_children 的类型为& Vec< __> ,并且在 match 分支的两个生命周期中,生命周期较短的一个将生存

Now new_children is of type &Vec<_> and it will live for the shorter of the two lifetimes of the match branches.

请注意,除非您在 match 的每个分支中初始化临时目录,否则都不能在其后使用 tmp_new ,因为这样会得到:

Note that unless you initialize the temporary in every branch of your match you cannot use tmp_new after it, because you will get:

可能未初始化的变量的使用: tmp_new

这篇关于如何解决“借入时的暂时价值下降"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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