0

I'm struggling with destructuring/auto dereferencing.

I have a snippet of code, which works and I kind of see why - a is mutable and we pass a mutable reference to match. In the match statement we have a pattern which expects a mutable reference, and we take inner variables which are references to avoid moving them out.

let x = vec![1, 2];
let y = vec![3, 4];
let mut a = (x, y);
match &mut a {
    &mut (ref aa, ref bb) => {}
}

I'm struggling to see why the following pattern works. I expect the pattern not to match to begin with, but it matches and aa and bb are both mutable references (no need for ref mut). I feel that this is some auto dereferencing at play:

match &mut a {
    (aa, bb) => {
        aa[0] = 2;
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Vismantas
  • 1
  • 1

1 Answers1

1

I feel that this is some auto dereferencing at play?

I wouldn't call it "auto" dereferencing because your intention to dereference the matched value is made explicit as part of your destructuring pattern. But yes, when you match a mutable reference against a pattern with a mutable reference it's the same as dereferencing the matched value. You can see this in action in this simpler code example:

fn main() {
    for num in &[1, 2, 3] {
        // type of `num` inside loop is &i32
        // explicit deref required for equality check
        if *num == 3 {
            println!("found 3");
        }
    }
    
    // implicit deref in destructuring pattern
    for &num in &[1, 2, 3] {
        // type of `num` inside loop is i32
        // no need for explicit deref operation now
        if num == 3 {
            println!("found 3");
        }
    }
}

playground

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98