在检查如何对Arc和Mutex变量进行打包时,我遇到了一个问题:看起来OK的代码在构建Mutex
的返回值时会生成“does not live long enough”错误。只需将 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()
拉出来,也会出现相同的错误。 - vikram2784MutexGuard
的生命周期比Mutex
更长(MutexGuard
借用了Mutex
)。不太清楚为什么! - vikram2784