Difference between match binding and match destructuring?

Viewed 305

Recently I was reading about the match keyword in the Rust Book. What confused me was the difference between Binding and Destructuring. In my understanding, both of these provide a way to access variables in an expression. Binding can specify a range matching, but you can achieve it with Destructuring and Guards. So can someone show some cases that only Binding can do or explain the real difference between these two concepts?

1 Answers

Here you can see one scenario when a binding is needed because destructuring doesn't satisfy our current need. If we simply destructure the struct we get access to the inner field of the struct. This means that the values used on the right hand side in the match arm won't have access to the methods defined on the struct.

In my example I also match against a specific value of ex.value, this is of course not necessary and can be done with a guard instead, this way is however more concise if the condition isn't very complex.

struct Example {
    some_value: i32,
    some_other_value: String
}

impl Example {
    pub fn some_fn(&mut self) {}
}

fn main() {
    let ex = Example { some_value: 42, some_other_value: "Foobar".to_string() };
    
    match ex {
        mut new_ex @ Example { some_value: 43, .. } => new_ex.some_fn(),
        Example { some_value: first, some_other_value: second } => println!("first value: {}\nSecond value: {}", first, second),
    }
}
Related