rust - 为什么在可变引用上进行模式匹配时不需要`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;
}
}
解决方案
我觉得这是一些自动取消引用?
我不会将其称为“自动”取消引用,因为您取消引用匹配值的意图已明确作为解构模式的一部分。但是,是的,当您将可变引用与具有可变引用的模式匹配时,它与取消引用匹配的值相同。您可以在这个更简单的代码示例中看到这一点:
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");
}
}
}
推荐阅读
- c# - 引用资源文件的方法的 NUnit 测试用例
- c# - MVC 2.0 中列表的绑定列表
- laravel - 模型关系的推荐 Laravel 路由结构
- node.js - 纽约市不显示数组中函数的覆盖率
- amazon-cloudwatch - 获取 JSON 日志文件中的数组项计数
- eclipse-rcp - Perspectiveswitcher 不会创建命令对象来切换视角
- imagemagick - 调整大小时如何保持图像纵横比?
- xamarin - FlexLayout 内 StackLayout 内的项目在 Xamarin Forms 中未垂直居中
- java - 这段代码有什么问题,它在必须时不会停止
- html - Django拒绝连接没有HTTP协议的HTML