我有一个叫做的函数new_vec.它通过对压缩矢量中的元素对执行元素运算,需要两个向量并创建一个新向量.
fn main() {
let v1s = vec![1, 0, 1];
let v2s = vec![0, 1, 1];
let v3s = new_vec(v1s, v2s);
println!("{:?}", v3s) // [1, 1, 2]
}
fn new_vec(v1s: Vec<i32>, v2s: Vec<i32>) -> Vec<i32> {
let mut v3s = Vec::<i32>::new();
for (v1, v2) in v1s.iter().zip(v2s.iter()) {
v3s.push(v1 + v2) // would also like to use -
}
v3s
}
Run Code Online (Sandbox Code Playgroud)
我希望有一个new_vec为共同二进制的操作,可以对两个整数,如使用功能+,-,/,*.
我该怎么做呢?我可以想象两种方式:宏和闭包.如何小例子来做到这一点的最佳方式,例如使用+和-将不胜感激.
我会通过一个关闭:
fn new_vec<F>(v1s: &[i32], v2s: &[i32], foo: F) -> Vec<i32>
where F: Fn(i32, i32) -> i32
{
let mut v3s = Vec::<i32>::new();
for (&v1, &v2) in v1s.iter().zip(v2s.iter()) {
v3s.push(foo(v1, v2))
}
v3s
}
fn main() {
let v1s = vec![1, 0, 1];
let v2s = vec![0, 1, 1];
let v3s = new_vec(&v1s, &v2s, |x, y| x - y);
let v4s = new_vec(&v1s, &v2s, |x, y| x + y);
println!("{:?}", v3s); // [1, -1, 0]
println!("{:?}", v4s); // [1, 1, 2]
}
Run Code Online (Sandbox Code Playgroud)
注意前两个参数的变化; 如果你的函数不需要使用它的参数,那么引用比Vectors 更好 - 在这种情况下&[i32].
这种实现效率不高,因为生成的Vector是递增的; 如果您按如下方式修改它以减少分配数量会更好:
fn new_vec<F>(v1s: &[i32], v2s: &[i32], foo: F) -> Vec<i32>
where F: Fn(i32, i32) -> i32
{
v1s.iter().zip(v2s.iter()).map(|(&x, &y)| foo(x, y)).collect()
}
Run Code Online (Sandbox Code Playgroud)