Rustlers Atom 1.9: Numbers and conversions
April 18, 2026•379 words
Rust keeps numeric conversions explicit and typed. You choose how to convert so the compiler can enforce safety.
as
as performs a primitive cast right now, even if information may be lost (e.g., narrowing or sign changes). Use it when you know what you’re doing.
fn main() {
let a: u16 = 500;
let b: u8 = a as u8; // 500 → 244 (wraps modulo 256)
let x: f32 = 3.9;
let y: i32 = x as i32; // truncates toward zero → 3
println!("{b}, {y}");
}
- Integers → integers: wrap or truncate to fit.
- Floats → integers: truncate (no rounding).
- Pay attention to sign:
-1_i8 as u8becomes255.
as is fine for indexing with usize or for well-understood casts—but prefer safer abstractions for data from the outside world.
From / Into
Use From and Into when the conversion cannot fail. They’re trait-based and compose well.
use std::convert::From;
let n: i64 = 42;
let m: i128 = i128::from(n); // From<i64> for i128
let k: i128 = n.into(); // Into picks the target from context
let s: String = String::from("hi");
let t: String = "ciao".into();
You’ll see From<T> for U whenever there is no risk (widening integer, owning/borrowing promotion, etc.). If From exists, Into is auto-implemented, so you can pick whichever reads better.
TryFrom / TryInto
Use TryFrom and TryInto the conversion might fail (narrowing integers, validated types). Both returns a Result.
use std::convert::{TryFrom, TryInto};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let big: i64 = 300;
let small: u8 = u8::try_from(big)?; // Err if out of range
let also: u8 = big.try_into()?; // same via TryInto
println!("{small}, {also}");
Ok(())
}
This is essential for robust APIs: you must handle the error path.
Strings / Numbers conversion
Strings aren’t numbers, so you parse them explicitly. Parsing is fallible by design, don’t unwrap() on untrusted input.
let port: u16 = "8080".parse()?; // Result<u16, ParseIntError>
let float: f64 = "3.14".parse().unwrap();
All numbers implement Display, so to_string() “just works.”
let s = 42.to_string(); // "42"
let hex = format!("{:#x}", 255); // "0xff"