问题
I'm trying to multiply each element from two different arrays. I mean, I have array1 = [i1 , i2] and array2 = [j1, j2] so I need to do (i1 * j1) + (i2 * j2). How can I approach this in Rust? I've been researching in The Book and saw some methods that possibly could help: map and fold. But I'm a bit lost. Thanks in advance!
fn sum_product(a: [f32], b: [f32]) -> [f32] {
unimplemented!();
}
fn main() {
let a: [f32; 2] = [2.0, 3.0];
let b: [f32; 2] = [0.0, 1.0];
}
回答1:
With a mix of zip and map:
fn sum_product(a: &[f32], b: &[f32]) -> f32 {
a.iter()
.zip(b.iter())
.map(|(a, b)| a * b)
.sum()
}
fn main() {
let a = [2.0, 3.0];
let b = [0.0, 1.0];
assert_eq!(3.0, sum_product(&a, &b));
}
来源:https://stackoverflow.com/questions/56930343/multiplying-elements-from-two-different-arrays