I want to implement the frequent math multiplication of a vector by a scalar: k * v = (k * v0, k * v1, k* v2..). The code is the following:
#[derive(Debug)]
struct V(Vec<i32>);
impl std::ops::Mul<V> for i32 {
type Output = V;
fn mul(self, v: V) -> V {
V(v.0.iter().map(|v| v * self).collect())
}
}
fn main() {
let v = V(vec![1,2]);
println!("{:?}", 3 * v);
}
This solution works, however I would like to avoid the definition of the struct V, and instead code something like that:
impl std::ops::Mul<Vec<i32>> for i32 {
type Output = Vec<i32>;
fn mul(self, v: Vec<i32>) -> Vec<i32> {
v.iter().map(|v| v * self).collect()
}
}
Which throws the following error:
only traits defined in the current crate can be implemented for arbitrary types
--> src/main.rs:45:1
|
45 | impl std::ops::Mul<Vec<i32>> for i32 {
| ^^^^^-----------------------^^^^^---
| | | |
| | | `i32` is not defined in the current crate
| | `Vec` is not defined in the current crate
| impl doesn't use only types from inside the current crate
|
= note: define and implement a trait or new type instead
Is possible to use the multiplication trait for foreign types?