Rust Basics

Why Rust exists, cargo, variables and mutability, scalar and compound types, functions and expressions, control flow, strings (String vs &str), vectors, and how Rust code is organised into crates and modules.

Beginner 2 min readLesson 1 of 9

Rust is a systems programming language that gives you C/C++-level performance and control without a garbage collector, while preventing whole classes of bugs — null pointer dereferences, use-after-free, double frees, data races — at compile time. It's used for browsers (Firefox), operating systems (Linux kernel drivers, Windows components), cloud infrastructure (AWS Firecracker, Cloudflare), CLIs (ripgrep, uv, ruff) and WebAssembly.

The price is a steeper learning curve, centred on ownership (Ownership).

Cargo: build tool and package manager

Shell
cargo new hello          # create a project (Cargo.toml + src/main.rs)
cargo run                # build and run (debug)
cargo build --release    # optimised build
cargo test               # run tests
cargo add serde          # add a dependency from crates.io
cargo clippy             # linter
cargo fmt                # formatter
Rust
// src/main.rs
fn main() {
    let name = "world";
    println!("Hello, {name}!");      // println! is a macro (note the !)
}

Variables and mutability

Variables are immutable by default:

Rust
let x = 5;
x = 6;                   // ✗ error: cannot assign twice to immutable variable

let mut count = 0;       // opt in to mutability
count += 1;

let spaces = "   ";
let spaces = spaces.len();   // shadowing: a NEW variable with the same name (can change type)

const MAX_POINTS: u32 = 100_000;   // compile-time constant; type required

Types

Rust is statically typed with strong inference.

CategoryTypes
Signed integersi8, i16, i32 (default), i64, i128, isize (pointer-sized)
Unsigned integersu8, u16, u32, u64, u128, usize (used for indexing and lengths)
Floatsf32, f64 (default)
Other scalarsbool, char (a 4-byte Unicode scalar value)
CompoundTuples (i32, f64, char), arrays [i32; 5] (fixed length, on the stack)
Rust
let tup: (i32, f64, char) = (500, 6.4, 'z');
let (a, b, c) = tup;            // destructuring
let first = tup.0;

let arr = [1, 2, 3, 4, 5];
let zeros = [0u8; 1024];        // 1024 zero bytes
arr[10];                        // panics at runtime: index out of bounds (no buffer overflow!)

Integer overflow panics in debug builds and wraps in release builds; use explicit methods when you mean it: x.wrapping_add(1), x.checked_add(1) (returns Option), x.saturating_add(1). There are no implicit numeric conversions: let y: u64 = x as u64;.

Functions and expressions

Rust
fn add(a: i32, b: i32) -> i32 {
    a + b                        // no semicolon: this expression is the return value
}

fn main() {
    let y = {
        let x = 3;
        x + 1                    // blocks are expressions
    };                           // y = 4
    let parity = if y % 2 == 0 { "even" } else { "odd" };   // if is an expression
}

Parameter types are always required; return types too (except (), the unit type). Adding a ; turns an expression into a statement that evaluates to () — a common early error.

Control flow

Rust
for i in 0..5 { }                        // 0,1,2,3,4   (0..=5 includes 5)
for (i, v) in vec.iter().enumerate() { }
while n > 0 { n -= 1; }
let result = loop {                      // loop can return a value via break
    counter += 1;
    if counter == 10 { break counter * 2; }
};
'outer: for x in 0..10 {
    for y in 0..10 {
        if x * y > 50 { break 'outer; }  // labelled break
    }
}

match number {                           // must be exhaustive
    1 => println!("one"),
    2 | 3 => println!("two or three"),
    4..=9 => println!("small"),
    n if n < 0 => println!("negative"),
    _ => println!("something else"),
}

Strings: String vs &str

The source of much early confusion:

String&str (string slice)
WhatAn owned, growable UTF-8 buffer on the heapA borrowed view into UTF-8 data somewhere
Mutable?Yes (if mut)No
ExamplesString::from("hi"), format!(…), s.to_string()String literals "hi", &s[0..2], &my_string
Use in function parametersRarelyUsually — accepts both
Rust
let mut s = String::from("hello");
s.push_str(", world");
let greeting: &str = &s;                 // borrow a String as &str
let word = &s[0..5];                     // slice by BYTE range — must be on char boundaries

fn shout(text: &str) -> String {         // take &str, return an owned String
    text.to_uppercase()
}
shout("hi"); shout(&s);

for c in "héllo".chars() { }             // iterate Unicode scalar values
"héllo".len();                           // 6 — length in BYTES, not characters

You can't index strings with s[0]: in UTF-8 a "character" may be several bytes, so Rust makes you choose bytes (as_bytes()), chars (chars()), or grapheme clusters (a crate).

Vectors and hash maps

Rust
let mut v: Vec<i32> = Vec::new();
v.push(1);
let v2 = vec![1, 2, 3];
let third = v2[2];                       // panics if out of bounds
let maybe = v2.get(10);                  // Option<&i32>: None, no panic

let doubled: Vec<i32> = v2.iter().map(|x| x * 2).collect();   // iterators and closures
let evens: Vec<&i32> = v2.iter().filter(|x| *x % 2 == 0).collect();

use std::collections::HashMap;
let mut scores: HashMap<String, u32> = HashMap::new();
scores.insert("ada".to_string(), 10);
*scores.entry("bob".to_string()).or_insert(0) += 5;     // upsert

Crates, modules and visibility

  • A crate is a compilation unit: a binary (main.rs) or a library (lib.rs). A package (one Cargo.toml) contains crates.
  • Modules organise code within a crate; items are private by default — pub makes them visible.
Rust
// src/lib.rs
pub mod geometry {
    pub struct Point { pub x: f64, pub y: f64 }
    pub fn distance(a: &Point, b: &Point) -> f64 {
        ((a.x - b.x).powi(2) + (a.y - b.y).powi(2)).sqrt()
    }
    fn helper() {}                      // private to this module
}

// src/main.rs
use mycrate::geometry::{self, Point};

Modules can live in separate files: mod geometry; loads src/geometry.rs or src/geometry/mod.rs.

Key takeaways
  • Rust offers C-level performance with compile-time memory and thread safety, no GC.
  • Cargo builds, tests, formats, lints and manages crates.io dependencies.
  • Variables are immutable unless declared mut; shadowing creates new bindings.
  • Blocks, if and match are expressions; the final expression without ; is the value.
  • String owns heap UTF-8 data; &str borrows it — take &str in parameters.
  • Code is organised in crates and modules; everything is private unless pub.