So with this code:
let mut x = 10;
let y = &mut x;
*y += 10; // Why do we need the dereference * symbol?
I don't get why we need this deference
*y += 10; since we don't need this symbol when we are printing
y onto the console so why do we need it when we need to change the value?
This is because
println! is a macro, and it's special. It will magically dereference things by itself.
If you called a regular function instead, you would have to pass
*y to pass the integer, rather than a reference to an integer.
Ah I see.
Right I get it.
Just to ensure I am clear on dereferences, so dereferencing simply means to take me to the address it is pointing to, in this case the value of
Actually it's not a magic but the
Display if the
T does so.
Any sufficiently advanced indirection is indistinguishable from magic
Usually yes. There are cases where Rust is more clever about this. Types can implement
Deref trait to customize what gets dereferenced. Also the combination of
&* is guaranteed not to do the silly thing of referencing a temporary dereference, but to be optimized into address/type manipulation that doesn't read memory behind the reference.
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.