I have problems understanding the ref
pattern in Rust. I am referring to https://rustbyexample.com/scope/borrow/ref.html
Here is the code I don't understand:
let point = Point { x: 0, y: 0 };
let _copy_of_x = {
// `ref_to_x` is a reference to the `x` field of `point`
let Point { x: ref ref_to_x, y: _ } = point;
// Return a copy of the `x` field of `point`
*ref_to_x
};
I get that the last let
expression(?) is some sort of pattern matching. So it's my understanding ref ref_to_x
should be equal to 0
, the x
value of the original point
.
But I don't understand what the ref
actually does. When I add some code like this:
println!("x: {}", point.x);
println!("ref_to_x: {}", ref_to_x);
println!("*ref_to_x: {}", *ref_to_x);
I always get 0
, so there doesn't seem to be a difference. Somehow I'd expect a memory address for ref_to_x
while *ref_to_x
might be the dereferenced value again.
I can replace both ref ref_to_x
and *ref_to_x
with myx
and the code still works. What's the difference? What does ref
do exactly?
edit: after reading dbaupps answer and doing some addition with ref_to_x
and *ref_to_x
things got a bit clearer; you cannot add an integer to ref_to_x
because it's a reference. I guess I got confused because there is no indication of a reference when you print one.