skip to content

In Rust, what do `300_i32 as u8`, `-1_i32 as u32` and `200_u8 as i8` evaluate to, and why does `as` never report the loss?

level: middleimportance: should knowfreq 64%

answer

  1. bits first, meaning second
  2. keep the low bits
  3. same width, same bits, new reading
  4. extend by sign or by zero

basics

~20 s

They give 44, 4294967295 and -56. An integer as cast truncates to the target's low bits, reinterprets the same bits across signedness, and sign- or zero-extends when widening; it is infallible by definition, so it cannot report anything.

solid answer

~40 s

`as` between integers is a bit-level operation with no failure path. Narrowing keeps the low bits: 300 is `0x12C`, so `300_i32 as u8` is `0x2C`, 44. Casting between types of the same width is a no-op on the bits, so `-1_i32 as u32` reads all ones as 4294967295, and `200_u8 as i8` reads `0xC8` as -56. Widening sign-extends a signed source and zero-extends an unsigned one, so `-1_i8 as i32` stays -1. Integer-to-float casts round to the nearest float, so `16_777_217_i64 as f32` becomes 16777216. Because the result is always a value, never an error, `as` is the wrong tool where a value might not fit; the fallible `TryFrom` conversions return an error instead. `as` also refuses some pairs outright: only `u8` can be cast to `char` (E0604).

code

rust · 16 lines
rust
fn main() {
    let units: i32 = 300;
    let refund: i32 = -1;
    let id: i64 = 16_777_217;

    println!("{}", units as u8); // 44: keeps the low 8 bits
    println!("{}", refund as u32); // 4294967295: same bits, read unsigned
    println!("{}", 200u8 as i8); // -56
    println!("{}", -1i8 as i32); // -1: sign-extended
    println!("{}", 200u8 as i32); // 200: zero-extended
    println!("{}", id as f32); // 16777216: nearest f32
    println!("{}", 97u8 as char); // a
    println!("{}", '€' as u32); // 8364
    println!("{}", '€' as u8); // 172: truncated code point
    println!("{:?}", char::from_u32(0xD800)); // None: a surrogate
}

go deeper

for a junior

Recall that as never fails: narrowing keeps the low bits, so 300 as u8 is 44, and -1 as u32 is the unsigned maximum.

for a middle

Explain the rules by width: truncate, reinterpret at the same width, sign- or zero-extend when widening, round to nearest for int to float, and only u8 to char.

for a senior

Spot the silent bugs in review: negative offsets cast to usize, amounts narrowed for a wire format, and 64-bit ids passed through f64 above 2^53.

for a principal

Set where as is allowed at all, widening only for instance, with Clippy's cast lints and fallible conversions enforcing the rest.

## What `as` is `as` is Rust's **primitive cast** operator. Between numeric types it is defined entirely by the Reference's numeric cast rules, and every rule produces a value: there is no `Option`, no `Result`, no panic, in debug or release. That is the root of the question. `as` cannot report a loss because, by definition, it has no way to fail at run time; whatever bits survive the rule are the answer. ## Integer to integer The rules depend on the two widths: | Source to target | Rule | Example | Result | |---|---|---|---| | wider to narrower | **truncate**: keep the low bits | `300_i32 as u8` | `44` | | same width, other signedness | **no-op**: same bits, reread | `-1_i32 as u32` | `4294967295` | | same width, other signedness | **no-op** | `200_u8 as i8` | `-56` | | narrower signed to wider | **sign-extend** | `-1_i8 as i32` | `-1` | | narrower unsigned to wider | **zero-extend** | `200_u8 as i32` | `200` | Working the first one through: 300 is `0b1_0010_1100` (`0x12C`). A `u8` keeps the low eight bits, `0x2C`, which is 44. The `-1_i32 as u32` case shows that **two's complement** makes signed and unsigned of the same width share a bit pattern: -1 is all ones, and all ones read as unsigned is the maximum, 4294967295. `200_u8` is `0xC8`; read as a signed `i8`, the top bit makes it 200 - 256 = -56. ## Integer to float, and `char` - **Integer to float** produces the closest representable float, rounding ties to even. An `f32` has a 24-bit significand, so `16_777_217_i64 as f32` is `16777216`. An `f64` holds every integer up to 2^53 exactly; above that, an `i64` or `u64` identifier silently loses its low digits. - **`u8` to `char`** is the only integer type `as` accepts for a `char` target: `97u8 as char` is `'a'`. `code as char` with `code: u32` fails with E0604, "only `u8` can be cast as `char`, not `u32`", and rustc suggests `char::from_u32`, which returns `Option<char>` because not every `u32` is a Unicode scalar value (surrogates such as `0xD800` are not). - **`char` to an integer** reads the code point and then applies the integer rules: `'€' as u32` is 8364, but `'€' as u8` truncates it to 172. - **`bool` to an integer** is allowed (`true as u8` is 1); the reverse is not: `1u8 as bool` fails with E0054, and rustc suggests comparing with zero. Float-to-integer casts follow their own saturating rule, covered separately with the sensor-reading case. ## Why this matters in code review Because `as` never fails, every narrowing or sign-changing cast in a pull request is a place where a value can change silently: 1. A length or index computed as `i64` and cast `as usize` turns -1 into `usize::MAX`. 2. A `u64` amount cast `as u32` for a wire format drops its high 32 bits. 3. A `u64` record id cast `as f64` for a JSON client loses precision above 2^53. The remedies are on other pages, so in one line each: the fallible `TryFrom` conversions (`u8::try_from(300_i32)` returns an error) belong to the conversion-traits material, and Clippy's allow-by-default `cast_possible_truncation`, `cast_sign_loss` and `cast_possible_wrap` lints point at exactly these casts. Widening casts that cannot lose information are the safe uses of `as`, and even those read more clearly as `u32::from(x)`. ## Where `as` is still the right tool Banning `as` outright overshoots. It remains the clearest choice in a few places: - **Deliberate bit manipulation**: taking the low byte of a word with `word as u8` when truncation is the point, in a checksum or a protocol encoder. - **Widening that cannot lose information**, where a `From` conversion would also work and `as` is shorter; some teams prefer `From` here so that a later type change turns a silent truncation into a compile error. - **Fieldless enum discriminants**: `Status::Ok as u16` reads the declared discriminant; enums are covered with their own material. - **Float to integer after a range check**, which follows its own saturating rule. The review question for every `as` is the same: can this value be outside the target's range, or have the wrong sign, at run time? If yes, the cast needs a check or a fallible conversion. ## A quick self-test - Does `as` ever panic on integers? No. - Does narrowing check the range? No, it keeps the low bits. - Is `-1_i32 as u32` an error? No, it is 4294967295. - Can `as` build a `char` from a `u32`? No, E0604; use `char::from_u32`.

  • Why does `'€' as u8` compile when `233u32 as char` does not?
    Casting a `char` to any integer type is allowed and applies the integer rules to its code point, so 8364 truncates to its low byte, 172. The reverse needs a valid Unicode scalar value, which only a `u8` (0 to 255) guarantees; for wider integers rustc reports E0604 and points to `char::from_u32`, which returns `Option<char>`.
  • An `i64` offset is cast with `as usize` before indexing; what happens when the offset is -1?
    The cast reinterprets the bits, so -1 becomes `usize::MAX` on a 64-bit target, and `v[offset]` then panics as out of bounds instead of the code rejecting the bad offset where it arrived. The fix is to reject negatives first, or use the fallible `usize::try_from` conversion.

  • 300_i32 as u8 saturates to 255.
  • as panics in debug builds when a value does not fit.
  • -1_i32 as u32 is a compile error because the value is negative.
  • Casting i64 to f64 is always exact.
  • Any integer can be cast to char with as.