Conversion with as
A variable is a labelled box, and its type is the shape of the box. A u8 box holds numbers from 0 to 255, and an i64 box holds huge signed numbers. Sometimes a number has to move into a box of another shape. For example, you add an i32 to an i64 or get a whole number from a fractional one.
Rust does not move numbers between types on its own, even when nothing is lost: let wide: i64 = small; with small of type i32 gives error[E0308]: mismatched types. The compiler wants every change of type to be visible in the code. That way a loss of data cannot hide in an unnoticed line.
The word as
You change the type explicitly, with the word as:
let n: i32 = 260;
let wide = n as i64;
println!("{wide}"); // 260
println!("{}", n as u8); // 4
println!("{}", 3.99_f64 as i32); // 3n as i64widens the number: anyi32fits into ani64, and the value does not change.n as u8narrows it: only what fits in 8 bits remains. For a positive number, that is the remainder of division by 256, so4is what remains of260.3.99_f64 as i32drops the fraction, and the result is3, not4.
Here the box picture stops working. When a real box overflows, the extra falls out beside it, and you can pick it up. When as narrows a number, the extra is gone without a trace.
as does not panic
as never reports an error and never panics, in any build. It does not stop at 255 like saturating_add; it quietly cuts off what does not fit, so narrowing loses data without a warning. Narrow with as only when you know for sure that the number fits into the new type. Widening is always safe: the value does not change.
The number in the example sits in a variable for a reason. In 260 as u8, the number itself gets the type u8, and the compiler answers that 260 does not fit into it.
Common mistake
Numbers of different integer types were added:
fn main() {
let a: i32 = 5;
let b: i64 = 10;
let sum = a + b; // ✗
println!("{sum}");
}error[E0308]: mismatched typesBoth numbers are whole, but their boxes have different shapes, and Rust will not add them. First you convert one number to the type of the other: a as i64 + b gives 15. Widening is safe: any i32 fits into an i64.
Key points
- Rust does not mix numbers of different types on its own: you change the type with
as. - Widening with
askeeps the value, and narrowing quietly cuts off what does not fit. asdoes not panic in any build, and it drops the fraction.