【问题标题】:How can I call `reciprocal` on the result of calling `sum`?如何在调用“sum”的结果上调用“reciprocal”?
【发布时间】:2018-10-06 13:37:10
【问题描述】:

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

【问题讨论】:

  • recip 未在 i32 上定义。您的第一个代码示例具有对 f32 的强制转换,而第二个没有该强制转换。此外,v 在第二个示例中成为 i32 也没有任何意义。

标签: rust


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    相关资源
    最近更新 更多