简体   繁体   English

Rust in Arc中的临时生命

[英]Temporary Lifetime in Arc in Rust

I am struggling to understand temporary lifetime concept in Rust. 我正在努力理解Rust中的临时生命周期概念。

Let's say I have the following struct with the Arc field: 假设我在Arc字段中具有以下结构:

struct MyStruct {
    arc_field: Arc<Mutex<i32>>,
}

When i try to access inner i32 field inside from the clone of the arc_field it is complaining about 当我试图从的克隆内访问内123-132场arc_field则抱怨

Temporary value dropped here while still borrowed 仍然借来的临时价值在这里下降

Here is how I am trying to retrieve it: 这是我尝试检索它的方式:

let my_field = my_struct.arc_field.clone().lock().unwrap();

Why is that I need to use let binding to increase it's lifetime? 为什么我需要使用let绑定来增加它的寿命?

Here is playground 这是游乐场

clone returns a new instance that you do not store inside a variable. clone返回一个新实例,您不将其存储在变量中。 So it is a temporary value. 因此,这是一个临时值。 You must store your copy inside a variable to make it non temporary: 您必须将副本存储在变量中,以使其非临时性:

let my_field = my_struct.arc_field.clone(); // You have a non temporary lifetime
let my_field = my_field.lock().unwrap();

You cannot use directly the cloned value because lock borrows it, and the borrow cannot outlive the value. 您不能直接使用克隆的值,因为lock借用它,并且借用不会超过该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM