我试图找到两个向量的点积:
fn main() {
let a = vec![1, 2, 3, 4];
let b = a.clone();
let r = a.iter().zip(b.iter()).map(|x, y| Some(x, y) => x * y).sum();
println!("{}", r);
}
Run Code Online (Sandbox Code Playgroud)
这失败了
error: expected one of `)`, `,`, `.`, `?`, or an operator, found `=>`
--> src/main.rs:4:58
|
4 | let r = a.iter().zip(b.iter()).map(|x, y| Some(x, y) => x * y).sum();
| ^^ expected one of `)`, `,`, `.`, `?`, or an operator here
Run Code Online (Sandbox Code Playgroud)
我也试过这些,所有这些都失败了:
let r = a.iter().zip(b.iter()).map(|x, y| => x * y).sum();
let r = a.iter().zip(b.iter()).map(Some(x, y) => x * y).sum();
Run Code Online (Sandbox Code Playgroud)
这样做的正确方法是什么?
mdu*_*dup 11
在map(),您不必处理迭代器返回的事实Option.这是由照顾map().你需要提供一个函数来获取两个借来的值的元组.你第二次尝试就接近了,但语法错误.这是正确的:
a.iter().zip(b.iter()).map(|(x, y)| x * y).sum()
Run Code Online (Sandbox Code Playgroud)
你的最终程序需要更多的注释和使用不稳定的功能,r.
fn main() {
let a = vec![1, 2, 3, 4];
let b = a.clone();
let r: i32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
println!("{}", r);
}
Run Code Online (Sandbox Code Playgroud)
关于闭包的更多信息传递给map:我写过...map(|(x, y)| x * y),但是对于更复杂的操作,你需要按如下方式分隔闭包体:{}
| 归档时间: |
|
| 查看次数: |
1408 次 |
| 最近记录: |