Skip to content

01. Rust Basics & Foundations

Every Rust program begins with understanding the core building blocks. Rust is a statically typed language, meaning the compiler must know the types of all variables at compile time.

Variables & Immutability

By default, variables in Rust are immutable. This encourages safe concurrent code.

let x = 5; // Immutable
// x = 6; // This would cause a compile-time error!

let mut y = 10; // Mutable
y = 11; // Allowed

Constants

Constants are always immutable and must be annotated with a type. They can be declared in any scope, including global.

const MAX_POINTS: u32 = 100_000;

Primitive Scalar Types

Rust has four primary scalar types:

  1. Integers: Signed (i8, i16, i32, i64, i128, isize) and Unsigned (u8, u16, u32, u64, u128, usize). Default is i32.
  2. Floating-Point: f32 and f64 (default).
  3. Boolean: bool (true or false).
  4. Character: char (4-byte Unicode Scalar Value).

Compound Types

  1. Tuples: Group together multiple values of different types.
    let tup: (i32, f64, u8) = (500, 6.4, 1);
    let (x, y, z) = tup; // Destructuring
    let five_hundred = tup.0; // Access by index
  2. Arrays: Fixed-size collection of elements of the same type, allocated on the stack.
    let a = [1, 2, 3, 4, 5];
    let first = a[0];

Functions

Functions use the fn keyword and require explicit type annotations for parameters and return types.

fn add(a: i32, b: i32) -> i32 {
    a + b // Expression: no semicolon means it returns this value
}

Control Flow

Rust supports if expressions, loop, while, and for.

let number = 3;
if number < 5 {
    println!("Condition met");
} else {
    println!("Condition not met");
}

// if is an expression!
let condition = true;
let x = if condition { 5 } else { 6 };

// For loops (idiomatic for iterating over collections)
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
    println!("Value: {}", element);
}

Next, we will explore the core concept that sets Rust apart: Ownership and Borrowing.