In this function that computes the average of a slice of i32
values I show two ways to compute the sum.
Is there any reason to prefer approach 1 over 2?
Maybe the main reason to use turbofish is in the middle of a chained expression rather than at the end.
Why is the type i32
lost by the iterator? It's not clear to me why I can't just use let sum = numbers.iter().sum();
. Why doesn't it know that the type of sum
is i32
based on the type of numbers
?
fn average_i32(numbers: &[i32]) -> f32 {
// Approach #1
let sum = numbers.iter().sum::<i32>();
// Approach #2
let sum: i32 = numbers.iter().sum();
sum as f32 / numbers.len() as f32
}