如何在调用sum的结果上调用reciprocal?

时间:2018-10-05 21:34:02

标签: rust

此代码给出了正确的输出: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

我也有asked this question on the Rust user's forum

1 个答案:

答案 0 :(得分:1)

我在论坛上找到了答案,喜欢在这里分享:

fn main() {
    let v = ((1..=5).map(|x: i32| x.pow(2)).sum::<i32>() as f32).recip();
    println!("The answer is: {}", v);
}