<分区>
考虑以下工作 code :
fn f() {
let xs = vec![(0, 0)];
let f = |j| xs[j];
let y = f(0usize);
}
以下variation不编译:
fn f() {
let xs = vec![(0, 0)];
let f = |j| xs[j].0;
let y = f(0usize);
}
失败如下:
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
要修复它,必须注释j
:
fn f() {
let xs = vec![(0, 0)];
let f = |j: usize| xs[j].0;
let y = f(0usize);
}
Closures don’t require you to annotate the types of the parameters or the return value like fn functions do.
为什么必须显式键入 j
?