How to implement the below trait for a vector of generic type Vec<T>
?
For example, how to implement the below (working) Difference
trait in a generic way (e.g. so that it is valid for Vec<i32>
, Vec<f32>
, Vec<f64>
)?
trait Difference {
fn diff(&self) -> Vec<f64>;
}
impl Difference for Vec<f64> {
fn diff(&self) -> Vec<f64> {
self.windows(2)
.map(|slice| (slice[0] - slice[1]))
.collect()
}
}
fn main() {
let vector = vec![1.025_f64, 1.028, 1.03, 1.05, 1.051];
println!("{:?}", vector.diff());
}
From looking at the documentation, it seems like it should be something along the lines of:
trait Difference<Vec<T>> {
fn diff(&self) -> Vec<T>;
}
impl Difference for Vec<T> {
fn diff(&self) -> Vec<T> {
self.windows(2)
.map(|slice| (slice[0] - slice[1]))
.collect()
}
}
fn main() {
let vector = vec![1.025_f64, 1.028, 1.03, 1.05, 1.051];
println!("{:?}", vector.diff());
}
However the above results in:
error: expected one of `,`, `:`, `=`, or `>`, found `<`
--> src/main.rs:2:21
|
2 | trait Difference<Vec<T>> {
| ^ expected one of `,`, `:`, `=`, or `>` here
I've tried a few other variations however all of them resulted in much longer error messages.