Reference & and dereference * for integers

So with this code:

fn main()
{
    let mut x = 10;
    let y = &mut x;

    *y += 10; // Why do we need the dereference * symbol?

    println!("{}", y);
}

I don't get why we need this deference * in *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.

1 Like

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 x?

1 Like

Actually it's not a magic but the &T implements Display if the T does so.

1 Like

Any sufficiently advanced indirection is indistinguishable from magic :slight_smile:

1 Like

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.

1 Like