Consider the following working code:
fn f() {
let xs = vec![(0, 0)];
let f = |j| xs[j];
let y = f(0usize);
}
The following variation does not compile:
fn f() {
let xs = vec![(0, 0)];
let f = |j| xs[j].0;
let y = f(0usize);
}
It fails as follows:
error[E0282]: type annotations needed
--> src/lib.rs:3:17
|
3 | let f = |j| xs[j].0;
| ^^^^^ cannot infer type
|
= note: type must be known at this point
To fix it, one must annotate j:
fn f() {
let xs = vec![(0, 0)];
let f = |j: usize| xs[j].0;
let y = f(0usize);
}
The Rust book says:
Closures don’t require you to annotate the types of the parameters or the return value like fn functions do.
Why must j be explicitly typed?