rusttypesannotationstype-inferencetype-annotation

Why rust fails type inference for Vec<_>


I don't understand why Rust fails to infer the type for Vec<_> in some cases. If I run this

fn main() {
    let v = vec![1, 2, 3];
    let s = v.iter().sum();
}

I get an error:

error[E0282]: type annotations needed
 --> src/main.rs:5:9
  |
5 |     let s = v.iter().sum();
  |         ^ consider giving `s` a type

so that I have to modify it to either

fn main() {
    let v = vec![1, 2, 3];
    let s = v.iter().sum::<i32>();
}

or

fn main() {
    let v = vec![1, 2, 3];
    let s: i32 = v.iter().sum();
}

Why the type inference fails here? It correctly gets that v is a Vec<i32> so if sum it's on that vector why does it need i32 to be annotated?


Solution

  • Iterator::sum() is generic over its return type. This allows you to e.g. sum an iterator of &i32s into an i32, since i32 impls Sum<&i32>. Because of that, the compiler cannot infer the return type.