为什么MutexGuard要求在结构中使用生命周期参数,而在函数返回类型中不需要? [英] Why does a MutexGuard require a lifetime parameter in structs but not in function return types?

查看:199
本文介绍了为什么MutexGuard要求在结构中使用生命周期参数,而在函数返回类型中不需要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想移动MutexGuard.从函数返回MutexGuard可以正常工作,而无需提供生命周期参数.但是,当将防护罩打包到一个结构中时,编译器需要为防护罩提供一个生命周期参数.

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()
    }
}

当我尝试将MutexGuard打包到一个结构中时:

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?

推荐答案

在Rust中,这或多或少是任意设计的决定.

This is more or less arbitrary design decision in Rust.

在函数中有 lifetime Elision ,编译器根据函数参数中引用的生存期来猜测结构可能具有的生存期.

In functions there's lifetime elision, where the compiler guesses what lifetime the struct could have based on lifetimes of references in function arguments.

拥有foo(&'a self) -> Struct<'a>时,只有一个生存期(除了'static).这是一个很常见的情况,Rust出于方便起见暗示了这一点:foo(&self) -> Struct.

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.

这篇关于为什么MutexGuard要求在结构中使用生命周期参数,而在函数返回类型中不需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆