rust - 如何将 &i32 转换为 f64?

标签 rust

我正在尝试解决 an exercise at the end of this chapter in the Rust Book .

这是一个代码示例:

fn mean(v: &Vec<i32>) -> f64 {
    let mut sum = 0.0;
    let mut count = 0.0;

    for val in v {
        sum += &f64::from(val);
        count += 1.0;
    }

    sum / count
}

fn main() {
    let v = vec![1, 2, 3, 4];

    println!("The mean is {}", mean(&v));
}

错误是:

error[E0277]: the trait bound `f64: std::convert::From<&i32>` is not satisfied
 --> src/main.rs:6:17
  |
6 |         sum += &f64::from(val);
  |                 ^^^^^^^^^ the trait `std::convert::From<&i32>` is not implemented for `f64`
  |
  = help: the following implementations were found:
            <f64 as std::convert::From<f32>>
            <f64 as std::convert::From<i16>>
            <f64 as std::convert::From<i32>>
            <f64 as std::convert::From<i8>>
          and 3 others
  = note: required by `std::convert::From::from`

我也尝试过使用 as 关键字,但没有帮助。

最佳答案

仅限

f64 implements From for i32 ,而不是 &i32(这是对 i32 的引用)。要使其正常工作,您需要取消引用 val

fn mean(v: &Vec<i32>) -> f64 {
    let mut sum = 0.0;
    let mut count = 0.0;

    for val in v {
        sum += f64::from(*val);
        count += 1.0;
    }

    sum / count
}

如果您尝试执行 val as f64,这同样适用,事实上,在这种情况下您会收到更有用的错误消息:

error[E0606]: casting `&i32` as `f64` is invalid
 --> src/main.rs:6:16
  |
6 |         sum += val as f64;
  |                ---^^^^^^^
  |                |
  |                cannot cast `&i32` as `f64`
  |                help: dereference the expression: `*val`

关于rust - 如何将 &i32 转换为 f64?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55080089/

相关文章:

rust - 解决参数特征缺乏相关方法的问题?

rust - 如何导入substrate_primitives 以使用sr25519?

optimization - 加快循环

winapi - 为什么WNetOpenEnum会得到ERROR_INVALID_ADDRESS(487)结果?

rust - "cannot move out of variable because it is borrowed"旋转变量时

architecture - 应用架构 : Problem with Mutable/Immutable reference

rust - 如何对 `cfg` 和 Cargo 使用条件编译?

rust - 丢弃最后一个发件人但收信人仍处于事件状态时,是否可以在Tokio MPSC中保留项目?

rust - 比较字节数组和向量

rust - 了解绑定(bind)和借用