Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to dereference a mutable reference in a match to change it?

Tags:

rust

I'm reading The Rust Programming Language and one thing is not clear:

let mut mut_value = 6;
match mut_value {
    ref mut m => {
        *m += 10;
        println!("We added 10. `mut_value`: {:?}", m);
    },
}

Why do we need to dereference it to change it? We already have a mutable reference.

like image 666
mmmm Avatar asked Jan 03 '23 03:01

mmmm


1 Answers

A reference is an address pointer. If you were to just do m += 10, you'd be changing the memory address (Rust doesn't let you do this without unsafe). What you want to do is change the value at m. So where's the value? Follow the pointer! You do this by dereferencing.

like image 142
jhpratt Avatar answered Jan 14 '23 13:01

jhpratt