rust-course
rust-course copied to clipboard
Question to <Mutiple-threading -> Condition Variables section -> demo code)
thread topic, there is a demo code as below
![image](https://user-images.githubusercontent.com/85712372/163472143-867e9bbc-0bd0-4ede-aca0-6c96260ca719.png)
The question is why ampersand, is it there intentionally?
@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.
@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 tolet 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
&
andref
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?
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.