How to safely and idiomatically convert numeric types in Rust?
Hi! I recently started learning Rust and encountered a problem with number conversion. In other languages (C++, Python) I just wrote `(int)float_var` or `int(float_var)` and it worked. But in Rust the compiler constantly complains.
Here's an example of code I'm trying to write:
```rust
fn main() {
let a: u8 = 10;
let b: u16 = 20;
let sum = a + b; // Error: cannot add `u16` to `u8`
let pi: f64 = 3.14159;
let int_pi: u32 = pi; // Error: expected `u32`, found `f64`
let x: i32 = 100;
let y: u32 = x; // Error: expected `u32`, found `i32`
}
```
I understand that Rust is strongly typed, but how do I properly perform such conversions? I've heard about `as`, but it behaves dangerously on overflow. Are there safe and idiomatic ways? I need
No answers yet.
Log in to leave an answer