5

An attempt to pattern match a tuple within a map:

fn main() {
    let z = vec![(1, 2), (3, 4)];
    let sums = z.iter().map(|(a, b)| a + b);
    println!("{:?}", sums);
}

produces the error

error[E0308]: mismatched types
 --> src/main.rs:3:30
  |
3 |     let sums = z.iter().map(|(a, b)| a + b);
  |                              ^^^^^^ expected reference, found tuple
  |
  = note: expected type `&({integer}, {integer})`
             found type `(_, _)`

It is possible to use this syntax in some varied form, or must I write:

fn main() {
    let z = vec![(1, 2), (3, 4)];
    let sums = z.iter()
        .map(|pair| {
            let (a, b) = *pair;
            a + b
        })
        .collect::<Vec<_>>();
    println!("{:?}", sums);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Synesso
  • 37,610
  • 35
  • 136
  • 207

1 Answers1

10

The key is in the error message:

  |
3 |     let sums = z.iter().map(|(a, b)| a + b);
  |                              ^^^^^^ expected reference, found tuple
  |

It is telling you that map accepts its argument by reference, thus you need a reference in the pattern:

fn main() {
    let z = vec![(1, 2), (3, 4)];
    let sums = z.iter().map(|&(a, b)| a + b);
    //                       ^
    println!("{:?}", sums);
}

And that's it.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Matthieu M.
  • 287,565
  • 48
  • 449
  • 722