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.

Casting explicitly turns a value into another compatible type. In Rust, use `as` followed by the target type. This is useful because Rust treats different types as distinct, even when both are integers. section 1.3

A `u8` is an integer from 0 to 255 and can be cast to a `char`. An `i32` cannot be cast directly to `char`: the compiler reports an error. Cast it to `u8` first, then to `char`. section 1.3

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

The two casts turn 100 into a `u8` and then a `char`. The program prints `d`, the character at number 100. section 1.3

Watch out for smaller types

Casting a large number to a smaller type can change its value. For example, `256 as u8` produces 0, not 255. section 1.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Works through chained casts and a narrowing hazard without describing conversion internals.
Examples
Demonstrates converting 100 to `d` and casting 256 to `u8`.
What you can do after
Apply casting with Rust’s `as` operator and recognize that a smaller target type can change a value.
How it connects
Connects casting to integer types, characters, Unicode, and compiler errors.

Also explained in

Compare how 22 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.