匹配元组作为映射的输入

问题描述 投票:5回答:1

尝试模式匹配地图中的元组:

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

产生错误

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

可以以某种不同的形式使用这种语法,或者我必须写:

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);
}
rust
1个回答
10
投票

关键是在错误消息中:

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

它告诉你map通过引用接受它的参数,因此你需要在模式中引用:

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

就是这样。

© www.soinside.com 2019 - 2024. All rights reserved.