Why
let x = 1;
let y = &x;
let z = y;
Instead of
let x = 1;
let y = &x;
let z = &x;
Why
let x = 1;
let y = &x;
let z = y;
Instead of
let x = 1;
let y = &x;
let z = &x;
You might want to provide a bit more context. Both snippets are semantically equivalent, shared references have copy semantics (z does not "reference a reference" as from your title, but copies the reference to x from y).
So
let z = y;
is equivalent to
let z = &y.clone();
and
let z = &x;
but not to
let z = &y;
Yes, that is exactly how you can reference y. z will have the type &&i32 in this case.
I see. What would the use cases for &&type references be?
You sometimes have to deal with &&T in call-back based APIs, like when you are iterating over an Iterator<Item=&T> and use Iterator::find, for example, which takes a callback with &Item as its argument. Otherwise I don't recall having to deal with references-to-references very often. It is generally not a very useful construct, as references are trivially copyable.
Thank you very much, this has all been really helpful.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.