rust - 为什么 Rust 不能在给定序列的显式类型时推断 sum 的结果

标签 rust

<分区>

下面的代码无法推断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? ,但是在这种情况下,没有为序列指定类型。

最佳答案

This seems to be implying that this should be possible. Or have I misinterpreted this suggestion?

我认为这是一种误解。

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

它说你可以通过明确指定类型来去掉涡轮鱼,也就是做:

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

在这方面,您的主要功能可以写成:

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

关于rust - 为什么 Rust 不能在给定序列的显式类型时推断 sum 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49250494/

相关文章:

rust - 为什么一致性规则会引发错误 "the type parameter must be used as the type parameter for some local type"?

stack - 从向量中重复 pop() 项目的更简洁的方法是什么?

rust - 是否可以声明一个表示特征的关联类型?

rust - 如何使用Option::或引用Option?

curl - 使用 curl 向 Actix 服务器发送 POST 请求失败,返回 "400 Bad Request"

git - 我可以在 git 存储库中添加一个作为子目录的依赖包吗?

generics - 使用 AsRef 返回包含在输入包装器类型中的引用

rust - 在 Rust 中计算两个 f64 向量的点积的最快方法是什么?

rust - 未为f64实现RawData

rust - 如何同时声明多个可变变量?