Type annotation in methods & casting numbers

I am building a function to calculate the average value of a vector of numbers. The signature of such function is fn calculate_average(values: Vec<i32>) -> f64. I have tried to implement it in the following manner:

fn calculate_average(values: Vec<i32>) -> f64 {
    (values.iter().sum() as f64) / (values.len() as f64)


The problem is that I get the following error:

cannot infer type for type parameter `S` declared on the associated function `sum`

My understanding is that the compiler needs to know the type produced by the method sum() at compile time in order to determine if it can be cast into a f64 and it can not infer it.

Is this right? If so, how can I annotate such variable? I know I could create an additional variable and annotate it like:

let total: i32 = values.iter().sum();
total as f64 / values.len() as f64

but I was wondering if there's a way to annotate this variable without explicitly declaring it.


1 Like

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.