Rust Number Conversion - Don't Follow the Book...
Bottom-Line Up Front: I think as
should be harder to use for Integer conversion in Rust. I recommend you use TryFrom/TryInto instead. Here’s how I recommend doing it (more complete example of right/wrong at the end):
use std::convert::TryInto;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let orig: u64 = u64::MAX;
let ti_u64: u64 = orig.try_into()?;
let ti_i64: i64 = orig.try_into()?;
let ti_u32: u32 = orig.try_into()?;
Ok(())
}
I’m at an intermediate level with the Rust programming language. I’ve done a year of adventofcode, a medium-sized API server project, and little more. While refactoring some code in my project recently I got rid of some of my explicit string conversions and let the type inference system and From/Into do their jobs. Now that I’m more comfortable with reading code using From/Into patterns I think it’s actually simpler - I can easily understand and trust what the type inference system does in those instances. Before I had intuition about how the inference system worked, I didn’t trust it. I didn’t know what it was doing under the hood.
… Read more »