liveBook · Manning

As operator

As explained in Learn Rust in a Month of Lunches

The as operator performs explicit primitive-type conversions in Rust.

Rust’s `as` operator explicitly converts a value to another type. Write the value, followed by `as` and the desired type: `100 as u8` converts the integer to a `u8`. section 1.3

Not every direct conversion is allowed. A number inferred as `i32` cannot be cast directly to `char`; the compiler reports that only `u8` can be cast to `char`. You can cast 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 convert 100 first to `u8`, then to `char`. section 1.3

Alternatively, declare the number as `u8` from the start and cast it directly to `char`. Check the value before converting to `u8`: its maximum is 255, so larger values cannot be represented unchanged. section 1.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains chained casts, a compiler error, and examples involving values larger than the `u8` range.
Examples
Uses casts of 100 to `u8` and `char`, alongside `u8` conversions of 256 and 600.
What you can do after
Apply it to convert an integer to `u8` and then `char`, and recognize a rejected direct `i32`-to-`char` cast.
How it connects
Connects primitive types, integer types, character types, and compiler errors.

Also explained in

Compare how 4 books explain as operator →

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.