1
votes

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

1
Why do you clone the Arc?Francis Gagné
I want to use the ARC in between threads and so I clone the Arc and send it to spawned threads.Akiner Alkan

1 Answers

4
votes

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.