CYB225 Week 1 – Rust Essentials
Rust Overview
Systems language delivering C/C++-level speed with compile-time memory safety (no GC)
Eliminates null dereference, data races via ownership & borrow checker
Prime domains: systems SW, WebAssembly, game engines, blockchain
Installing & Tooling
Use rustup installer; sets up compiler + Cargo
Key Cargo cmds:
cargo new,cargo build,cargo runCentral package repo: crates.io; docs: “The Rust Book”
Core Syntax
Entry point:
fn main(); printing with macroprintln!Variables immutable by default:
let x = 5; make mutable withmutShadowing allows re-declare:
let x = x + 1Scalar types: signed/unsigned ints (e.g. i32, u8), floats f32/f64, bool, char
Compound: tuple
(i32, f64, char), array[i32; 5]Functions: explicit types, implicit final-expr return:
fn add(a: i32, b: i32) -> i32 { a + b }Control flow:
if/else,loop,while,for
Ownership & Memory
Each value has a single owner; dropped when owner out of scope
Move:
let s2 = s1;moves ownership, s1 invalidBorrowing:
&T(immut),&mut T(single mutable ref) — enforced by borrow checkerLifetimes annotate ref validity:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a strStack vs Heap handled automatically; no manual free
Data Structures & Pattern Matching
Struct:
struct User { username: String, … }Enum:
enum Message { Quit, Write(String) }matchoffers exhaustive pattern matching on enums/values
Error Handling
Unrecoverable:
panic!("msg")Recoverable:
Result<T,E>; useOk(val)/Err(err)
Project & Ecosystem
Project layout:
src/main.rs,Cargo.toml,target/Modules (
mod) organise code;pubexposes itemsCrates = reusable libraries; dependencies listed in
Cargo.toml
Concurrency
Threads via
std::thread::spawn; join withhandle.join()Ownership + borrowing rules make data-race-free concurrency the default
Key Takeaways
Memory safety, high performance, and fearless concurrency are Rust’s core strengths
Master ownership, borrowing, lifetimes early; they underpin all advanced features
Cargo & crates.io streamline builds and dependency management
Use
Resultfor normal error paths, reservepanic!for unrecoverable states