liveBook · Manning

As operator

As explained in Rust in Action: Systems programming concepts and techniques

The as operator is Rust syntax for explicitly converting a value to another type using a permitted cast.

The `as` operator explicitly casts a value to another permitted type. Rust requires compatible types before comparing values, so casting can make operands comparable. section 2.3.3

Cast before comparing

With `a: i32` and `b: u16`, `if a < b` does not compile. Cast the smaller value to `i32`: `if a < (b as i32) { println!("Ten is less than one hundred."); }` section 2.3.3

Use casts carefully:

  • Prefer converting a smaller integer type to a larger one, such as `u16` to `i32`; narrowing conversions are riskier. section 2.3.3
  • Expect surprising results from careless narrowing: `300_i32 as i8` produces `44`. section 2.3.3
  • Use `try_into()` with `Result` when a conversion may fail and `as` is too restrictive. section 2.3.3

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Explains syntax, promotion, narrowing risks, and fallible conversion, while deferring full traits and Result treatment.
Examples
Uses a mixed-type comparison, a narrowing integer cast, and a try_into conversion listing.
What it assumes
Assumes basic numeric values and comparisons while introducing type compatibility and conversion safety.
What you can do after
Apply explicit numeric casts to resolve compatible comparisons and recognize when fallible conversion is safer.
How it connects
Connects numeric types with comparisons, type safety, traits, error handling, and TryInto.

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 Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.