【问题标题】:Why can't Rust infer the result of sum when given an explicit type of a sequence [duplicate]为什么在给定序列的显式类型时,Rust 不能推断 sum 的结果
【发布时间】:2018-08-21 08:58:47
【问题描述】:

以下代码无法推断出s的类型

fn main() {
    let l: Vec<u32> = vec![];
    let s = l.iter().sum();
    println!("{:?}", s);
}

这是由 Rust by Example https://rustbyexample.com/std_misc/threads/testcase_mapreduce.html 中的某些东西激发的

// collect each thread's intermediate results into a new Vec
let mut intermediate_sums = vec![];
for child in children {
    // collect each child thread's return-value
    let intermediate_sum = child.join().unwrap();
    intermediate_sums.push(intermediate_sum);
}

// combine all intermediate sums into a single final sum.
//
// we use the "turbofish" ::<> to provide sum() with a type hint.
//
// TODO: try without the turbofish, by instead explicitly
// specifying the type of intermediate_sums
let final_result = intermediate_sums.iter().sum::<u32>();

这似乎暗示这应该是可能的。还是我误解了这个建议?

注意我看到了一些相关的票证,例如Why can't Rust infer the resulting type of Iterator::sum?,但在这种情况下,没有为序列指定类型。

【问题讨论】:

  • 这与您链接的问题相同。该问题中也给出了序列的类型(它是Range&lt;i32&gt;)。
  • 我与 Rust by Example 团队确认这是一个拼写错误。

标签: rust


【解决方案1】:

这似乎暗示这应该是可能的。还是我误解了这个建议?

我认为这是一种误解。

// TODO: try without the turbofish, by instead explicitly
// specifying the type of intermediate_sums
let final_result = intermediate_sums.iter().sum::<u32>();

它说你可以通过明确指定类型来不使用turbo fish,也就是说:

let final_result: u32 = intermediate_sums.iter().sum();

在这方面,你的 main 函数可以写成:

fn main() {
    let l: Vec<u32> = vec![];
    let s: u32 = l.iter().sum();
    println!("{:?}", s);
}

【讨论】:

  • 这不是“指定intermediate_sums的类型”,即求和的数组,而不是求和的结果吗? OP 已经这样做了
  • 嗯,我不确定。即使 intermediate_sumsVec&lt;u32&gt;,编译器仍然无法推断类型并给出建议“考虑给 final_result 一个类型”
猜你喜欢
  • 2021-07-05
  • 1970-01-01
  • 2019-01-09
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多