【发布时间】:2019-05-04 07:24:05
【问题描述】:
在检查How do I box Arc and Mutexed variables? 时,我遇到了一个问题,即看起来正常的代码在从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(),
}
}
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
【问题讨论】:
-
奇怪!只拉出
body.lock(),也会出现同样的错误。 -
似乎它希望
MutexGuard比Mutex寿命更长(MutexGuard借用Mutex)。不知道为什么!
标签: rust language-lawyer