In my understanding a reference is a pointer
Yes, a reference is just a pointer with special borrow-checking semantics. Pointers, and thus references, are just addresses in memory (and sometimes a size as well but that's irrelevant for this answer), which means that they essentially have a value of their own, separate from the value that they "point to" or "reference." That's why code like this can work:
fn main() {
let num1 = 1;
let num2 = 2;
let mut num_ref = &num1;
dbg!(num1, num2, num_ref); // num1 and num2 are 1 and 2 and num_ref is &1
num_ref = &num2;
dbg!(num1, num2, num_ref); // num1 and num2 are 1 and 2 and num_ref is &2
}
The values under the reference don't change, but the reference itself changes.
So, &mut &T
is a mutable reference to an immutable reference, which means you can change the reference underneath the mutable reference:
fn make_reference_one(r: &mut &i32) {
*r = &1;
}
fn main() {
let mut num_ref = &2;
dbg!(num_ref); // is &2
make_reference_one(&mut num_ref);
dbg!(num_ref); // is now &1
}