liveBook · Manning

Data conversion

As explained in Learn Rust in a Month of Lunches

Type casting explicitly converts a value from one Rust type to another compatible type.

A cast uses `as` to turn a value into another type. Rust keeps types distinct, even when both are integers. For example, a `u8` can be cast to a `char`: values from 0 to 255 include numbers assigned to common characters. section 1.3

fn main() {
    let my_number = 100;
    println!("{}", my_number as u8 as char);
}

Here, `my_number` is first cast from `i32` to `u8`, then from `u8` to `char`. Casting it directly from `i32` to `char` produces a compiler error. The value 100 prints as `d`. section 1.3

Check the destination type’s range before casting. A `u8` holds 0 through 255, but casting 256 to `u8` gives 0—not 255. section 1.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Works through `as` syntax, a rejected direct cast, a corrected two-step cast, and an out-of-range result.
Examples
Shows 100 becoming `d` through `u8` and `char`, and 256 becoming 0 when cast to `u8`.
What it assumes
Introduces `u8` ranges and character numbers before casting; assumes no prior knowledge of casts.
What you can do after
Apply it via Rust’s `as` operator to make supported conversions and recognize an unexpected result when casting to `u8`.
How it connects
Connects casting to integer types, `char`, Unicode character numbers, and compiler errors.

Also explained in

Compare how 21 books explain data conversion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.