rust - 如何在调用“sum”的结果上调用“reciprocal”?
问题描述
这段代码给出了正确的输出:0.018181818
fn main() {
let v: i32 = vec![1, 2, 3, 4, 5].iter().map(|&x: &i32| x.pow(2)).sum();
println!("{}", (v as f32).recip());
}
当我尝试将它们加入单行时,我失败了,因为之后的输出类型sum
与所需的输入类型不同recip
:
fn main() {
let v: i32 = vec![1, 2, 3, 4, 5]
.iter()
.map(|&x: &i32| x.pow(2))
.sum()
.recip();
println!("{}", v);
}
error[E0282]: type annotations needed
--> src/main.rs:2:18
|
2 | let v: i32 = vec![1, 2, 3, 4, 5]
| __________________^
3 | | .iter()
4 | | .map(|&x: &i32| x.pow(2))
5 | | .sum()
| |______________^ cannot infer type for `S`
|
= note: type must be known at this point
我也在Rust 用户论坛上问过这个问题。
解决方案
我在论坛上找到了答案,并在这里分享:
fn main() {
let v = ((1..=5).map(|x: i32| x.pow(2)).sum::<i32>() as f32).recip();
println!("The answer is: {}", v);
}
推荐阅读
- javascript - 材质图标上的 matTooltip
- python - 根据给定列 pandas 中的缺失值将行从一个数据帧添加到另一个数据帧
- node.js - 有没有办法强制 mineflayer.js 机器人更新它的位置?
- ios - 禁用播放、下一首曲目、上一首曲目按钮现在正在播放通知屏幕上的信息
- python - 顶点:TypeError:Python3 中不可能的类建议
- javascript - 如何显示 JSON 文件对象?
- highcharts - 选择图表上的默认视图为 1 个月而不是全部
- c# - 实体框架 - 如何在没有表单的情况下添加数据库条目
- python - 创建简单 TCP 客户端时出现错误
- sql-server - 如何将一条记录生成为两条记录,然后将它们插入到表中?