Avatar ·

How to safely and idiomatically convert numeric types in Rust?

Hi everyone! I just started learning Rust after C++ and Python, and I have a serious problem with number conversion. In C++, I was used to just writing `(int)my_float` or `static_cast(value)`, and it worked. But in Rust, the compiler constantly complains. Here's a specific situation: I'm writing a program that calculates the arithmetic mean. I have a vector of integers, and I need to get the result as a floating-point number. ```rust fn average(numbers: &[i32]) -> f64 { let sum: i32 = numbers.iter().sum(); sum / numbers.len() as f64 // This works, but looks awkward } ``` It seems to work, but I feel like this is wrong. Additionally, when I try to do the reverse conversion — from `f64` to `i32` — the compiler gives an error that you can't just do it.