Why does a MutexGuard require a lifetime parameter in structs but not in function return types? [duplicate]

非 Y 不嫁゛ 提交于 2019-12-22 18:26:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!