为什么生锈失败的类型推理vec< _>
我不明白为什么Rust无法推断 vec< _>
的类型。如果我运行此问题,
fn main() {
let v = vec![1, 2, 3];
let s = v.iter().sum();
}
我会收到一个错误:
error[E0282]: type annotations needed
--> src/main.rs:5:9
|
5 | let s = v.iter().sum();
| ^ consider giving `s` a type
因此我必须将其修改为任何一种
fn main() {
let v = vec![1, 2, 3];
let s = v.iter().sum::<i32>();
}
类型
fn main() {
let v = vec![1, 2, 3];
let s: i32 = v.iter().sum();
}
推理在此处失败的原因?它正确地得到 v
是 vec&lt; i32&gt;
,因此,如果 sum
在该向量上,为什么需要 i32
被注释?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要扩展Chayim Friedman的答案,请考虑以下代码:
游乐场
您可以看到
main
函数与示例仅在s
的类型中有所不同。因此,如果没有这种类型,它可能是模棱两可的 - 请注意,消费者
struct> struct> struct> struct(以及其实现)很可能在另一个板条箱中,而不是由您控制。因此,生锈迫使您做出明确的选择,确切地汇总到什么。To expand on the Chayim Friedman's answer, consider the following code:
Playground
You can see that the
main
function differs from your example only in the type ofs
. Therefore, without this type it's potentially ambiguous - note that theConsumer
struct (and, consequently, its implementation) could very well be in another crate, not controlled by you. Therefore, Rust forces you to make an explicit choice, what exactly to sum into.iterator> iterator :: sum(sum() /code>
对其返回类型是通用的。这使您可以将
impl&amp; i32
s的迭代器汇总到i32
中,因为i32
i32sum&sum&lt&lt&lt;
。因此,编译器无法推断返回类型。Iterator::sum()
is generic over its return type. This allows you to e.g. sum an iterator of&i32
s into ani32
, sincei32
implsSum<&i32>
. Because of that, the compiler cannot infer the return type.