问题
I'd like to move a MutexGuard
around. Returning a MutexGuard
from a function works fine without giving a lifetime parameter. But when packing the guard into a struct, the compiler demands a lifetime parameter for the guard.
The following code compiles without errors:
struct Queue {
queue: Mutex<Vec<i32>>,
}
impl Queue {
pub fn get_mutex_guard(&self) -> MutexGuard<Vec<i32>> {
self.queue.lock().unwrap()
}
}
When I try to pack the MutexGuard into a struct:
struct QueueHandle {
handle: MutexGuard<Vec<i32>>,
}
the compiler complains about a missing lifetime parameter:
error[E0106]: missing lifetime specifier
--> mutex-guard.rs:8:13
|
8 | handle: MutexGuard<Vec<i32>>
| ^^^^^^^^^^^^^^^^^^^^ expected lifetime parameter
To my understanding, the requirements for lifetime parameters should be the same for function return types and structs. What am I missing here?
回答1:
This is more or less arbitrary design decision in Rust.
In functions there's lifetime elision, where the compiler guesses what lifetime the struct could have based on lifetimes of references in function arguments.
When you have foo(&'a self) -> Struct<'a>
there's only one lifetime possible (apart from 'static
). This is such a common case that Rust allows this to be implied for convenience: foo(&self) -> Struct
.
Definition of references in structs wasn't deemed to be common and unambiguous enough to also have elided lifetimes, and the desire to have explicit lifetime definitions won.
来源:https://stackoverflow.com/questions/50955374/why-does-a-mutexguard-require-a-lifetime-parameter-in-structs-but-not-in-functio