types - 为什么这个闭包参数需要显式类型?

标签 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说:

Closures don’t require you to annotate the types of the parameters or the return value like fn functions do.

为什么必须显式键入 j

最佳答案

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

然而,在您的第二个示例中,您尝试访问 xs[j].0,为此编译器需要知道 xs[j] 的类型以便了解如何处理 .0

关于types - 为什么这个闭包参数需要显式类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56677371/

相关文章:

c++ - C++中string和char[]类型的区别

serialization - 添加 Serialize 属性以从第三方库键入

rust - 如何在第一个 None 值上停止无限迭代器?

rust - 如何在 Rust 中选择合适的 trait 实现?

c++ - 存储不同类型的数据c++

java - 使用正确的数字数据类型

postgresql - column1 的索引 = x AND column2 <= y ORDER BY column3 DESC

php - 将原始数据类型传递给函数参数

Rust 等同于 Swift 对协议(protocol)的扩展方法?

rust - 从对象池中借用时解决省略的静态生命周期