user1056805
user1056805

Reputation: 2933

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

When iterating over an array of tuples, why does Rust not destructure the tuples? For example:

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

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

leads to the error:

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

Upvotes: 7

Views: 3063

Answers (1)

fjh
fjh

Reputation: 13081

The problem is that your pattern (a, b) is a tuple of type (usize, usize), while your iterator returns references to tuples (i.e. &(usize, usize)), so the typechecker rightly complains.

You can solve this by adding an & in your pattern, like this:

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

Upvotes: 16

Related Questions