Data Types & Casting

🦀 Rust Lesson 3 Beginner

Rust is statically typed. The compiler can usually infer variable types, but they must be resolved before compilation. Type casting is strictly explicit.

1 Scalar Types & casting with 'as'

Rust primitives include booleans, chars, and numeric types (signed integers `i8`-`i128`, unsigned `u8`-`u128`, floats `f32` and `f64`).

Explicit Casting: Rust does not support implicit casting. You cannot add a float to an integer. You must convert values explicitly using the **`as`** keyword: `let ratio = score as f64 / total as f64;`.

2 Cast Operations Code

Let's run a program illustrating numeric casting:

Rust — Casting ▶ Run Code
fn main() {
    let int_val: i32 = 42;
    let float_val: f64 = 3.14;

    // Explicit casting using the 'as' keyword
    let result = int_val as f64 * float_val;

    println!("Result: {}", result);

    // Integer casting (truncates decimals)
    let int_price = float_val as i32;
    println!("Int Price: {}", int_price);
}
3 Code Challenge
Challenge: Define a `u8` integer. Cast it to `u16` and then to `f32`. Perform division with a float variable and print the final value.