In short, does passing reference A of another reference B to function parameter causing automatic dereference?
Here's the story...
When reading stack & heap - complex example, I am confused at the following explanation, please see img01 -> img02.
Since variable e
is a reference to variable d
, so the value of e
is represented in -> 9 (i read it as: go to memory address of d)
, this is ok.
But why does the parameter f
of baz
get value of "data address referred by d
", instead of the value of e
? I thought the value of f
should be -> 9
as well?
If f
is what img02 says it is, then does it mean that "dereference" happened here automatically? Since e
contains a reference to d
, d
contains a reference to some heap address, and the passing of e
to f
results in f
has a reference to the heap address?
Yes, a dereference is done automatically. This is called Deref
coercion.
This is the mechanism that allows for implicitly converting one reference to another. Some notable uses:
&&T
-> &T
&&&&&&&&T
-> &T
&Box<T>
-> &T
&Vec<T>
-> &[T]
See more explanation in the Rust book: Treating Smart Pointers Like Regular References with the Deref
Trait or in the Rust reference: Type Coercions.