首页 > 解决方案 > 为什么在可变引用上进行模式匹配时不需要`ref mut`?

问题描述

我正在为解构/自动取消引用而苦苦挣扎。

我有一段代码,它有效,我有点明白为什么 -a是可变的,我们将可变引用传递给match. 在match语句中,我们有一个期望可变引用的模式,并且我们采用作为引用的内部变量以避免将它们移出。

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

我很难理解为什么以下模式有效。我希望该模式一开始就不匹配,但它匹配 andaa并且bb都是可变引用(不需要ref mut)。我觉得这是一些自动取消引用:

match &mut a {
    (aa, bb) => {
        aa[0] = 2;
    }
}

标签: rustpattern-matchingdestructuring

解决方案


我觉得这是一些自动取消引用?

我不会将其称为“自动”取消引用,因为您取消引用匹配值的意图已明确作为解构模式的一部分。但是,是的,当您将可变引用与具有可变引用的模式匹配时,它与取消引用匹配的值相同。您可以在这个更简单的代码示例中看到这一点:

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");
        }
    }
}

操场


推荐阅读