Sub topic 11
Converting between types safely
This chapter assumes you know let bindings, the integer and float types, and how to read a simple compiler error. Rust never converts between numeric types implicitly. You pick a conversion tool, and each tool states how it handles values that do not fit.
The four tools
| Tool | Can fail? | Typical use |
|---|---|---|
| `as` | No, it truncates or rounds silently | Low-level casts where you accept the result |
| `From` / `into` | No | Lossless widening, such as `i32` to `i64` |
| `TryFrom` / `try_into` | Yes, returns `Result` | Narrowing or sign changes |
| `parse` | Yes, returns `Result` | Text to a number |
A first example
fn main() {
let big: i32 = 300;
let truncated = big as u8;
let parsed: u32 = "42".parse().unwrap();
let wide = i64::from(big);
let narrow = u8::try_from(big);
println!("{truncated} {parsed} {wide} {}", narrow.is_err());
}This prints 44 42 300 true. Each line shows a different behavior:
big as u8keeps only the low 8 bits of 300. That gives 44, with no warning."42".parse()returns aResult. The target type,u32here, tells the compiler what to parse.i64::from(big)always works, so it returns the value directly and not aResult.u8::try_from(big)returnsErrbecause 300 does not fit in au8.
Why `as` is risky
as never fails, so it can hide bugs. Its rules depend on the types involved:
- Integer to a narrower integer: the high bits are dropped.
- Integer to a different sign: the bit pattern is reinterpreted, so
-1i32 as u32is 4294967295. - Float to integer: the value is truncated toward zero and clamped to the target's range.
NaNbecomes 0. - Integer to float: the value is rounded to the nearest representable one.
fn main() {
println!("{}", -1i32 as u32);
println!("{}", 3.99_f64 as i32);
println!("{}", 1e20_f64 as i32);
println!("{}", f64::NAN as i32);
}This prints 4294967295, 3, 2147483647, and 0.
Lossless conversions with `From` and `into`
From is implemented only where no information is lost. i64::from(5i32) compiles. i32::from(5i64) does not, so the compiler stops you from narrowing by accident.
into is the same conversion written from the other side. The target type must be known from context:
fn main() {
let small: u8 = 200;
let medium: u32 = small.into();
let text: String = "hello".into();
println!("{medium} {text}");
}Fallible conversions with `TryFrom`
TryFrom returns a Result. The error says the value was out of range. You handle it like any other Result:
use std::convert::TryFrom;
fn main() {
for value in [200_i32, 300, -5] {
match u8::try_from(value) {
Ok(byte) => println!("{value} fits: {byte}"),
Err(_) => println!("{value} does not fit in u8"),
}
}
}The output is 200 fits: 200, then 300 does not fit in u8, then -5 does not fit in u8. A negative value fails because u8 is unsigned.
Parsing text
parse works for any type that implements FromStr, including all the numeric types, bool, and char. It fails on bad input, so handle the Result:
fn main() {
for text in ["42", "-7", "4x2", ""] {
match text.parse::<i32>() {
Ok(n) => println!("{text:?} -> {n}"),
Err(e) => println!("{text:?} failed: {e}"),
}
}
}The turbofish ::<i32> names the target type when no annotation on a let provides it. Whitespace is not trimmed, so " 42" fails. Call trim() first if the input may have it.
Choosing a tool
Common errors
mismatched typeswhen adding ani32to ani64. Convert one side explicitly, usually withFrom.type annotations neededonparse()orinto(). Add aletannotation or a turbofish.- Calling
.unwrap()on aparseresult for user input. The program panics on bad input. Match on theResultinstead.
Exercise
What does u8::try_from(256_i32) return, and what does 256_i32 as u8 produce?
Show answer
u8::try_from(256_i32) returns an Err, because 256 is larger than u8::MAX (255). 256_i32 as u8 produces 0, because as keeps only the low 8 bits and 256 has none of them set.
Exercise
Which tool should you use to turn a u16 into a u64, and why?
Show answer
Use u64::from(value) or value.into(). A u16 always fits in a u64, so the conversion cannot fail. From is implemented only for lossless conversions, so the compiler also confirms that no data is lost.