Akiner Alkan
Akiner Alkan

Reputation: 6918

Temporary Lifetime in Arc in Rust

I am struggling to understand temporary lifetime concept in Rust.

Let's say I have the following struct with the Arc field:

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

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?

Here is playground

Upvotes: 1

Views: 690

Answers (1)

Boiethios
Boiethios

Reputation: 42829

clone returns a new instance that you do not store inside a variable. 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.

Upvotes: 4

Related Questions