为什么在遍历元组数组时元组没有被解构?

Why are tuples not destructured when iterating over an array of tuples?

在遍历元组数组时,为什么 Rust 不解构元组?例如:

let x: &[(usize, usize)] = &[...];

for (a,b) in x.iter() {
    ...
}

导致错误:

error: type mismatch resolving `<core::slice::Iter<'_, (usize, usize)> as core::iter::Iterator>::Item == (_, _)`:
expected &-ptr,
found tuple [E0271]

问题是你的模式 (a, b) 是类型 (usize, usize) 的元组,而你的迭代器 returns 引用元组(即 &(usize, usize)),所以类型检查器正确的抱怨。

您可以通过在模式中添加 & 来解决此问题,如下所示:

for &(a,b) in x.iter() {