Tuple as input to the map

Template attempt to match a tuple inside a map:

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

causes an 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 `(_, _)` 

This syntax can be used in some varied form, or I have to 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); } 
+5
source share
1 answer

The key is in the error message:

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

Tells you that map accepts its argument by reference, so you need a link in the template:

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

What is it.

+10
source

Source: https://habr.com/ru/post/1258871/


All Articles