为什么此闭包参数需要显式类型?

时间:2019-06-20 00:02:57

标签: types rust

请考虑以下工作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);
}

Rust book说:

  

不要求您注释参数的类型或   返回值就像fn函数一样。

为什么必须显式键入j

1 个答案:

答案 0 :(得分:0)

如@Stargateur建议的duplicate中所述,Rust需要知道索引的类型,以便可以确定结果的类型。在第一个示例中,这不是问题,因为您没有使用xs[j]或闭包的结果,因此编译器可以随意将它们保留为“某种尚未定义的类型”,并且可以对其进行优化,需要知道类型。

但是,在第二个示例中,您尝试访问xs[j].0,为此编译器需要知道xs[j]的类型才能知道如何处理.0。 / p>

相关问题