Writing a function that takes generic numerical parameters and return a float


I’ve been using Rust for some time now; this little function however is shattering my nerves. The function below should generate the mean of a vector of generic numeric values and return a float value (as it is sensible for mean values).

This is the solution, I came up with. Sadly, it is not working.

pub fn mean<T: Num, U: Float + From<T>>(vals: &Vec<T>) -> U {
	let len = vals.len();
	vals.iter().fold(U::zero(), |acc: U, x: &T| acc + *x)

My guess is that the Rust compiler fails in converting the *x value from the generic type T to the type U which obviously makes sense as the compiler doesn’t now how to cast the corresponding values.

Of course, the function is still missing the division to calculate the mean value.

I’d like to know if this is even the correct approch to solving this or if there is a better one (probably always returning an f64 instead of a generic value with the Float trait).

I’ll be glad for any advice someone may give me.


I’d not cast each element on every iteration of the fold:

vals.iter().fold(T::default(), |acc, x| acc + *x).into()

This turns the value into a U at the end instead of during every iteration. If you want to keep it as you originally proposed:

vals.iter().fold(U::zero(), |acc, x| acc + (*x).into())

This actually became a nice challenge, but I couldn’t get it to work for f32 and f64
Take a look to understand what I mean…


You can do something like this, using a few more traits from the num crate.

1 Like