相关疑难解决方法(0)

为什么我会在返回值中得到"活得不够长"?

在检查如何选中Arc和Mutexed变量?我遇到了一个问题,在这个问题中,看起来正常的代码在从a构造返回值时会产生"不够长时间"的错误Mutex.简单地从lock().unwrap()访问对象中删除访问权限可以消除错误 - 但我想了解为什么Rust在这种情况下抱怨生命周期问题.

我能够将代码剪切成一个非常简单的重现器:第一个函数编译好,第二个函数生成错误消息,它们几乎相同.

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(),
    }
}
Run Code Online (Sandbox Code Playgroud)
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 …
Run Code Online (Sandbox Code Playgroud)

language-lawyer rust

7
推荐指数
2
解决办法
297
查看次数

标签 统计

language-lawyer ×1

rust ×1