Appearance
类型转换1: exercises/conversions/using_as.rs
题目
rust
// using_as.rs
//
// Type casting in Rust is done via the usage of the `as` operator. Please note
// that the `as` operator is not only used when type casting. It also helps with
// renaming imports.
//
// The goal is to make sure that the division does not fail to compile and
// returns the proper type.
//
// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
fn average(values: &[f64]) -> f64 {
let total = values.iter().sum::<f64>();
total / values.len()
}
fn main() {
let values = [3.5, 0.3, 13.0, 11.7];
println!("{}", average(&values));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn returns_proper_type_and_value() {
assert_eq!(average(&[3.5, 0.3, 13.0, 11.7]), 7.125);
}
}
Rust中的类型转换是通过使用as
运算符来完成的。请注意,as
运算符不仅仅在类型转换时使用,它还可以在重命名导入的时候使用。
本题目的目标是确保除法不会编译失败,并且返回正确的类型。
题目解析
错误信息提示我们cannot divide f64
by usize
,也就是f64无法和usize相除。
函数average
的作用是求平均数,由于values
里面所有元素都是f64
类型,最终返回值类型也是f64
类型,但是values.len()
是一个usize
类型,f64
无法和usize
相除,我们需要将values.len()
转换为f64
,可以使用values.len() as f64
。
rust
fn average(values: &[f64]) -> f64 {
let total = values.iter().sum::<f64>();
total / values.len()
total / values.len() as f64
}