liveBook · Manning

As operator

As explained in Learn Rust in a Month of Lunches

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

Use `as` to explicitly convert a value to another primitive type. For example, `my_number as char` asks Rust to treat a number as a character. The source type matters: an ordinary `let my_number = 100` is inferred as `i32`, which cannot be cast directly to `char`. section 1.3

error[E0604]: only u8 can be cast as char, not i32
 --> src\main.rs:3:20
  |
3 |     println!("{}", my_number as char);
  |                    ^^^^^^^^^^^^^^^^^

The compiler points to the cast and explains the fixable problem: only `u8`, not `i32`, can be cast to `char`. section 1.3

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

Convert to `u8` first, then to `char`: `my_number as u8 as char`. Alternatively, declare `my_number: u8` from the start. section 1.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Works through a rejected cast and two corrections, without detailing conversion rules for every primitive type.
Examples
Shows `100` rejected as an `i32`-to-`char` cast, then converted through `u8`.
What it assumes
Introduces primitive and integer types before using `as`; assumes only basic familiarity with a variable declaration.
What you can do after
Apply it in Rust to correct the illustrated integer-to-character cast.
How it connects
Connects type inference, integer types, characters, and compiler errors.

Also explained in

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