将&i32转换为f64

时间:2019-03-09 17:32:19

标签: rust

我是生锈的新手。在本章末尾尝试解决一个练习:https://doc.rust-lang.org/book/ch08-03-hash-maps.html

这是一个代码示例:

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

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

2 个答案:

答案 0 :(得分:4)

Request.PathBaseimplements From for i32,而不是MapWnen(这是对f64的引用)。要使其正常工作,您需要“取消引用” &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
}

答案 1 :(得分:1)

您可以使用*val as f64取消引用变量。

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

    for val in v {
        sum += *val as f64;
        count += 1.0;
    }

    sum / count
}

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

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

另一种方法

fn main() {
    let v = vec![1, 2, 3, 4];
    let mean: f64 = v.iter().map(|&val| val as f64).sum::<f64>() / v.len() as f64;

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