mmmm
mmmm

Reputation: 3938

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

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.

Upvotes: 9

Views: 3183

Answers (1)

jhpratt
jhpratt

Reputation: 7120

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.

Upvotes: 18

Related Questions