gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:12:04 24 4
gpt4 key购买 nike

我正在尝试解决 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com