rust-course icon indicating copy to clipboard operation
rust-course copied to clipboard

Question to <Mutiple-threading -> Condition Variables section -> demo code)

Open Kangaxx-0 opened this issue 2 years ago • 3 comments

thread topic, there is a demo code as below

image

The question is why ampersand, is it there intentionally?

Kangaxx-0 avatar Apr 14 '22 20:04 Kangaxx-0

@Kangaxx-0 In Rust language, the following code is equivalent.

let x = &1;

and

let ref x = 1;

let y = *x;

and

let &y = x;

The let &(ref lock, ref cvar) = &*pair2; code is equivalent to

let tuple: &(Mutex<bool>, Condvar) = &*pair2; // note: type declaration
let (lock, cvar) = *tuple; // note: *
let lock = &lock;
let cvar = &cvar;

This seems a little verbose, so we use the & and ref syntax to quickly dereference and add references.

Rustln avatar Apr 15 '22 09:04 Rustln

@Kangaxx-0 In Rust language, the following code is equivalent.

let x = &1;

and

let ref x = 1;
let y = *x;

and

let &y = x;

The let &(ref lock, ref cvar) = &*pair2; code is equivalent to

let tuple: &(Mutex<bool>, Condvar) = &*pair2; // note: type declaration
let (lock, cvar) = *tuple; // note: *
let lock = &lock;
let cvar = &cvar;

This seems a little verbose, so we use the & and ref syntax to quickly dereference and add references.

Thanks for this explanation, I understood that line which doing a quick dereference, but I am trying to understand the necessity of references which is the ampersand, in other words, if I do let (ref lock, ref cvar) = *pair2;, it still works, Pair2 get moved into the new thread, then it will be automatically dropped when it is out of the scope, anything I misunderstood?

Kangaxx-0 avatar Apr 15 '22 22:04 Kangaxx-0

Yes, in this case, & it doesn't seem necessary. Now I can't understand the author's motivation. Your question is right. Of course, you don't have to pay too much attention to this point. Continue to study. I believe you will think clearly in the future. I also look forward to your answer at that time.

Rustln avatar Apr 16 '22 11:04 Rustln