I want to implement a default implementation of a trait MovingAverage
over some generic type Vec<T>
, but I'm obviously doing something wrong since I can make it work for the concrete type Vec<f64>
but not for the concrete type Vec<i32>
. Here's the output from the error:
error[E0599]: the method `sma` exists for struct `Vec<{integer}>`, but its trait bounds were not satisfied
--> src/main.rs:8:22
|
8 | let smai = numsi.sma(n);
| ^^^ method cannot be called on `Vec<{integer}>` due to unsatisfied trait bounds
|
::: /home/czar/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:397:1
|
397 | pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
| ------------------------------------------------------------------------------------------------ doesn't satisfy `Vec<{integer}>: MovingAverage`
|
= note: the following trait bounds were not satisfied:
`f64: AddAssign<{integer}>`
which is required by `Vec<{integer}>: MovingAverage`
`f64: SubAssign<{integer}>`
which is required by `Vec<{integer}>: MovingAverage`
Here's my code from ma.rs:
pub trait MovingAverage<Output = Vec<f64>> {
fn sma(&self, periods: usize) -> Output;
}
impl<T> MovingAverage for Vec<T>
where
T: Copy Num,
f64: AddAssign<T> SubAssign<T>,
{
fn sma(&self, periods: usize) -> Vec<f64> {
let mut sum = 0f64;
let mut ma = Vec::<f64>::new();
for i in 0..self.len() {
if i >= periods {
ma.push(sum / periods as f64);
sum -= self[i - periods];
}
sum = self[i];
}
ma
}
}
My main.rs
let numsf = vec![5., 10., 3., 9., 8., 7.];
let mut numsi = vec![2, 4, 3, 5, 1, 1];
let n = 2;
let smaf = numsf.sma(n);
let smai = numsi.sma(n); // doesnt work here
What's going on in my error, and what would be the proper way to go about implementing a trait over a generic type without having to implement the trait for each concrete type? Thanks in advance, and kindly let me know if you need any further clarification.
CodePudding user response:
Maybe a better bound would be T: Into<f64>
. Then you can simply convert each element into a f64
when you access it. Also, if you implement the trait for [T]
instead of Vec<T>
, it will also work for slices. Try this:
impl<T: Copy Into<f64>> MovingAverage for [T] {
fn sma(&self, periods: usize) -> Vec<f64> {
let mut sum = 0f64;
let mut ma = Vec::<f64>::new();
for i in 0..self.len() {
if i >= periods {
ma.push(sum / periods as f64);
sum -= self[i - periods].into();
}
sum = self[i].into();
}
ma
}
}
(Side note: I think your code may unintentionally ignore the last element of the input)