为什么我会“寿命不足"?返回值? [英] Why do I get "does not live long enough" in a return value?

查看:145
本文介绍了为什么我会“寿命不足"?返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在检查>如何将Arc和Mutexed装箱变量?,我遇到了一个问题,其中看起来不错的代码在从Mutex构造返回值时会生成寿命不足"错误.只需将lock().unwrap()访问从返回对象中拉出即可消除该错误-但我想了解为什么Rust在这种情况下会抱怨生命周期问题.

In examining How do I box Arc and Mutexed variables?, I ran into an issue where code that looks OK is generating a "does not live long enough" error while constructing a return value from a Mutex. Simply pulling the lock().unwrap() access out of the return object removes the error - but I'd like to understand why Rust is complaining about a lifetime issue in this case.

我能够将代码简化为一个非常简单的复制器:第一个函数编译正常,第二个函数生成错误消息,并且它们几乎相同.

I was able to cut the code down to a very simple reproducer: The first function compiles OK, the second generates the error message, and they're almost identical.

use std::sync::Mutex;

pub struct Response {
    resp: String,
}

pub fn get() -> Response {
    let body = Mutex::new("a".to_string());
    let x: std::sync::MutexGuard<_> = body.lock().unwrap();
    Response { resp: x.clone() }
}

pub fn get2() -> Response {
    let body = Mutex::new("a".to_string());
    Response {
        resp: body.lock().unwrap().clone(),
    }
}

error[E0597]: `body` does not live long enough
  --> src/lib.rs:16:15
   |
16 |         resp: body.lock().unwrap().clone(),
   |               ^^^^ borrowed value does not live long enough
17 |     }
18 | }
   | - `body` dropped here while still borrowed
   |
   = note: values in a scope are dropped in the opposite order they are created

推荐答案

正如Stargateur的回答所指出的,其原因是临时人员的一生.尽管Rust还没有完整的规范,但是语言参考仍然是相当不错的,至少提供了一个了解行为的提示.这是部分中有关临时寿命的相关部分:

As pointed out in Stargateur's answer, the reason for this is the lifetime of temporaries. While Rust does not have a full specification yet, the language reference still is quite good and at least gives a hint to understand the behaviour. Here is the relevant part from the section about temporary lifetimes:

[T]临时值的生存期通常为

[T]he lifetime of temporary values is typically

  • 最内在的封闭语句;块的尾部表达式被认为是包围该块的语句的一部分,或者
  • 如果在if的条件表达式或while表达式的循环条件表达式中创建了临时变量,则条件表达式或循环条件表达式.
  • the innermost enclosing statement; the tail expression of a block is considered part of the statement that encloses the block, or
  • the condition expression or the loop conditional expression if the temporary is created in the condition expression of an if or in the loop conditional expression of a while expression.

函数第二个版本中最里面的body.lock().unwrap()语句是return表达式.上面的规范指出,此表达式是包含该语句的语句的考虑部分",在这种情况下实际上并不存在,但它仍然给出了正确的主意:删除函数体本地的所有变量在返回表达式中的任何临时对象之前被删除,因此在借用body的MutexGuard之前,将body删除.您发现的修复程序可确保将临时变量在body之前删除,因为局部变量的删除顺序大致与创建时相反.

The innermost enclosing statement of body.lock().unwrap() in the second version of your function is the return expression. The spec above states that this expression is "considered part of the statement that encloses the block", which doesn't really exist in this case, but it still gives the right idea: All variables local to the function body are dropped before any temporaries in the return expression is dropped, so body is dropped before the MutexGuard that borrows body. The fix you found makes sure the temporary is dropped before body, since local variables are dropped roughly in reverse order of their creation.

这篇关于为什么我会“寿命不足"?返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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