尝试模式匹配地图中的元组:
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);
}
关键是在错误消息中:
|
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);
}
就是这样。