Sub topic 11
Converting between types safely
Rust never converts between types behind your back. You choose a conversion tool, and each tool makes a different promise about what happens when the value does not fit. This chapter covers the four tools (as, From/Into, TryFrom/TryInto, and parse) and how to pick between them.
Prerequisites
This chapter assumes you know the integer, float, bool, and char types from earlier chapters. It also assumes you can read Result and match at a basic level. You can run every example with cargo run or rustc.
No implicit conversions
Many languages widen numbers automatically. Rust does not, even when the conversion would be lossless.
fn main() {
let small: u8 = 10;
let wide: u32 = 5;
// let sum = small + wide; // error[E0308]: mismatched types
let sum = u32::from(small) + wide;
println!("{sum}");
}The compiler rejects the commented line because u8 and u32 are different types. Requiring a visible conversion means every place where a value could change meaning is marked in the source.
The `as` cast
as is the primitive cast. It works only between a fixed set of built-in types, and it never fails at runtime. It always produces some value, and that value is not always the one you wanted.
fn main() {
let big: i32 = 300;
println!("{}", big as u8); // 44
println!("{}", -1i32 as u32); // 4294967295
println!("{}", 200u8 as i8); // -56
println!("{}", 3.99_f64 as i32); // 3
println!("{}", -5.0_f64 as u8); // 0
println!("{}", 1e10_f64 as i32); // 2147483647
println!("{}", f64::NAN as i32); // 0
println!("{}", 16_777_217_i32 as f32); // 16777216
println!("{}", 97u8 as char); // a
println!("{}", 'A' as u32); // 65
println!("{}", true as i32); // 1
}The rules behind those outputs:
| Cast | Behavior |
|---|---|
| Integer to a narrower integer | Keeps the low bits and drops the rest (`300 as u8` is 44). |
| Integer to an integer of the same width but different sign | Reinterprets the same bits (`-1i32 as u32` is 4294967295). |
| Narrower integer to a wider integer | Sign-extends signed sources and zero-extends unsigned ones. This is lossless. |
| Float to integer | Truncates toward zero, **saturates** at the target's minimum and maximum, and turns NaN into 0. |
| Integer to float | Rounds to the nearest representable float. Large values lose precision. |
| `u8` to `char` | Allowed, because every byte value is a valid `char`. |
| `char` to integer | Gives the Unicode scalar value, truncated if the target is narrower than `u32`. |
| `bool` to integer | `false` is 0 and `true` is 1. |
Casting from float to integer saturating is defined behavior. Older Rust versions treated out-of-range floats as undefined behavior, but that was fixed.
Several conversions are not allowed with as at all. You cannot cast an integer to bool (write n != 0), and you cannot cast a u32 to char (use char::from_u32).
`From` and `Into`: conversions that cannot fail
From<T> is a trait for conversions that always succeed. The standard library implements it only where no information is lost. For numbers, that means widening within the same signedness, unsigned to a strictly wider signed type, and integers to floats that can hold every value exactly.
fn main() {
let a = i64::from(7i32); // signed widening
let b = u32::from(200u8); // unsigned widening
let c = i16::from(200u8); // unsigned to wider signed
let d = f64::from(3i32); // i32 fits exactly in f64
let e = u32::from('a'); // char to its code point
let f = char::from(65u8); // u8 is always a valid char
let g = String::from("hello"); // not numeric, same trait
println!("{a} {b} {c} {d} {e} {f} {g}");
}The output is 7 200 200 3 97 A hello.
Some conversions have no From impl, and that absence is informative. There is no From<i32> for u8 (it can overflow) and no From<i64> for f64 (an i64 can have more than 53 significant bits, which an f64 cannot hold). If the compiler says "the trait From<i64> is not implemented for f64", the conversion is lossy and you must choose another tool.
Implementing From gives you Into for free. Into is most useful in function signatures, where it lets callers pass any type that converts to what you need.
fn average(a: impl Into<f64>, b: impl Into<f64>) -> f64 {
(a.into() + b.into()) / 2.0
}
fn main() {
println!("{}", average(3i32, 4.5f32));
}This prints 3.75. Both an i32 and an f32 convert losslessly to f64, so both are accepted.
`TryFrom` and `TryInto`: conversions that can fail
When a value might not fit, TryFrom returns a Result. The standard library implements it for every integer pair that lacks a From impl. Both traits are in the prelude in the 2021 edition and later. In the 2018 edition you must write use std::convert::TryFrom; first.
fn to_byte(n: i32) -> Result<u8, String> {
u8::try_from(n).map_err(|e| format!("{n} does not fit in u8: {e}"))
}
fn main() {
println!("{:?}", to_byte(200));
println!("{:?}", to_byte(300));
println!("{:?}", to_byte(-1));
let index = usize::try_from(5i32).unwrap();
println!("{index}");
let clamped: u8 = 300i32.try_into().unwrap_or(u8::MAX);
println!("{clamped}");
}The output is:
Ok(200)
Err("300 does not fit in u8: out of range integral type conversion attempted")
Err("-1 does not fit in u8: out of range integral type conversion attempted")
5
255try_into is the method form. It needs a known target type, either from an annotation as above or from how the result is used. The error type for integer conversions is TryFromIntError. It carries no detail about the value, so include the value in your own message if you need it.
TryFrom is also the right tool for u32 to char, through char::try_from(u32). Not every u32 is a valid Unicode scalar value, because surrogates and values above 0x10FFFF are excluded.
What `TryFrom` does not cover
There is no TryFrom<f64> for integers. To convert a float safely, do the rounding and range check yourself.
fn float_to_u8(x: f64) -> Option<u8> {
let r = x.round();
if r.is_nan() || r < 0.0 || r > 255.0 {
None
} else {
Some(r as u8) // safe: r is in 0..=255
}
}
fn main() {
println!("{:?}", float_to_u8(3.6));
println!("{:?}", float_to_u8(300.0));
println!("{:?}", float_to_u8(f64::NAN));
}This prints Some(4), None, and None. The as cast is acceptable here because the check just above it guarantees the cast cannot truncate or saturate.
`parse`: from text to a value
str::parse converts a string slice into any type that implements FromStr. It always returns a Result, because text can be malformed. Tell the compiler the target type with an annotation or with the turbofish syntax ::<T>.
fn main() {
let inputs = ["42", " 7 ", "-1", "", "99999999999", "abc"];
for s in inputs {
match s.trim().parse::<u32>() {
Ok(n) => println!("{s:?} -> {n}"),
Err(e) => println!("{s:?} -> error: {e}"),
}
}
let pi: f64 = "3.14".parse().unwrap();
let flag = "true".parse::<bool>().unwrap();
let ch = "x".parse::<char>().unwrap();
println!("{pi} {flag} {ch}");
}The output is:
"42" -> 42
" 7 " -> 7
"-1" -> error: invalid digit found in string
"" -> error: cannot parse integer from empty string
"99999999999" -> error: number too large to fit in target type
"abc" -> error: invalid digit found in string
3.14 true xThree details matter in practice:
parsedoes not trim whitespace." 7".parse::<u32>()fails, so calltrim()first, especially on input read from a terminal, which ends with a newline.- A leading
+is accepted for integers, but underscores, hex prefixes such as0x, and thousands separators are not. Useu32::from_str_radix("ff", 16)for other bases. -1is an error for an unsigned target. It is not wrapped around the wayaswould do it.
Choosing a conversion
The same logic as a table:
| Situation | Tool | Failure behavior |
|---|---|---|
| Lossless numeric widening | `From` / `Into` | Cannot fail |
| Possibly out-of-range integer | `TryFrom` / `try_into` | Returns `Err` |
| Text to a value | `parse` | Returns `Err` |
| Intentional bit-level change or float rounding | `as` | Never fails, may change the value |
| Clamp instead of fail | `try_into().unwrap_or(MAX)` or the `saturating_*` methods | Substitutes a default |
Common errors
Using as for array indexes. Writing arr[i as usize] with a negative i produces a huge index, and the program panics with an out-of-bounds message that hides the real cause. Convert with usize::try_from(i) and handle the error.
Forgetting a type for parse or try_into. The error is "type annotations needed". Add ::<T> or annotate the binding.
Unwrapping on user input. .parse().unwrap() panics on bad input. Use match, ?, or unwrap_or with a sensible default.
Assuming float conversions are exact. i32 to f32 with as loses precision above 2^24, as the 16,777,217 example showed. f64::from(i32) is exact, which is why it exists.
Casting before a range check. Writing (x as u8) < 256 never works, because the cast already destroyed the information. Check on the original, wider type, then convert.
Exercise
What do 300i32 as u8, u8::try_from(300i32), and "300".parse::<u8>() each produce?
Show answer
300i32 as u8 produces the value 44, because it keeps only the low 8 bits (300 minus 256). u8::try_from(300i32) returns Err(TryFromIntError) because 300 does not fit in a u8. "300".parse::<u8>() returns an Err whose message is "number too large to fit in target type".
Exercise
Why does f64::from(i32_value) compile but f32::from(i32_value) does not? What would you write for the second case, and what is the risk?
Show answer
Every i32 fits exactly in an f64 (53 bits of mantissa), so the standard library provides a lossless From impl. An f32 has only 24 bits of mantissa, so some i32 values cannot be represented exactly and no From impl exists. You would write value as f32, and the risk is that large values are rounded (for example, 16,777,217 becomes 16,777,216).
Exercise
Write a function parse_percent(s: &str) -> Option<u8> that returns Some(n) only when s, after trimming whitespace, parses as an integer from 0 to 100, and None otherwise.
Show answer
fn parsepercent(s: &str) -> Option<u8> {
let n: i32 = s.trim().parse().ok()?;
let n = u8::tryfrom(n).ok()?;
if n <= 100 { Some(n) } else { None }
}
Parsing as i32 first lets values such as "-5" and "300" parse successfully, and try_from then rejects anything outside 0 to 255. The final comparison enforces the 0 to 100 limit. Each failure becomes None through .ok()?.