Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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]
like image 460
user1056805 Avatar asked Mar 13 '15 18:03

user1056805


1 Answers

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() {
like image 134
fjh Avatar answered Nov 02 '22 06:11

fjh