How to satisfy trait bounds for Vec<{integer}>?

I'm trying to implement the following:

pub trait CentralMoment<Output = f64>
where
    Output: Copy,
{
    fn mean(&self) -> Output;
}

impl<T: Copy> CentralMoment for [T]
where
    T: Copy + Sum + Div<f64, Output = f64>,
{
    fn mean(&self) -> f64 {
        let sum: T = self.iter().copied().sum();
        sum / self.len() as f64
    }
}

I can make it work for Vec<f64> but I'm doing something wrong since I can't make it work for Vec<i32>. I get the following compile error:

error[E0599]: the method `mean` exists for struct `Vec<{integer}>`, but its trait bounds were not satisfied
   --> src/lib.rs:143:26
    |
143 |         let avgi = numsi.mean();
    |                          ^^^^ method cannot be called on `Vec<{integer}>` due to unsatisfied trait bounds
    |
    = note: the following trait bounds were not satisfied:
            `<{integer} as Div<f64>>::Output = f64`
            which is required by `[{integer}]: CentralMoment`
            `{integer}: Div<f64>`
            which is required by `[{integer}]: CentralMoment`

How can I satisfy the trait bounds for Vec<{integer}>?

There are no integer types which define division by a floating-point number.

If you're trying to do things generically over numbers, you'll probably want num-traits — Rust math library // Lib.rs

1 Like

Ah, ok. That makes sense. Thanks.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.