I have a function called add_vec
. It takes two vectors and creates a new one, by performing an elementwise add on the pair of elements from the zipped vectors.
extern crate num;
use num::traits::Num;
fn add_vec<N: Num>(v1s: Vec<N>, v2s: Vec<N>) -> Vec<N> {
let mut v3s = Vec::new();
for (v1, v2) in v1s.iter().zip(v2s.iter()) {
v3s.push(v1 + v2)
}
v3s
}
#[cfg(test)]
mod tests {
use super::add_vec;
#[test]
fn it_works() {
let v1s = vec![1, 0, 3];
let v2s = vec![0, 1, 1];
let v3s = add_vec(v1s, v2s);
assert_eq!(v3s, vec![1, 1, 4]);
}
}
The problem is that I end up with the following error message:
error[E0369]: binary operation `+` cannot be applied to type `&N`
--> src/lib.rs:14:18
|
14 | v3s.push(v1 + v2)
| ^^
|
note: an implementation of `std::ops::Add` might be missing for `&N`
--> src/lib.rs:14:18
|
14 | v3s.push(v1 + v2)
| ^^
I know this is answered in Requiring implementation of Mul in generic function but I do not understand why I need to implement the Add
trait. As if there are numbers that cannot be added...
Is there a way to solve this without implementing Add
? I want to create a version of add_vec
that uses -
, %
, *
, /
instead of +
, and implementing the respective traits for each operation sounds like a drudge. I'm only interested in signed integers and floats, so perhaps there exists a trait for these subtypes of num?
My Cargo.toml
for convenience:
[package]
name = "minimal_example_2"
version = "0.1.0"
authors = ["User"]
[dependencies]
num = "0.1.36"