CODY ← Back to Courses
🦀

Rust — Safety & Performance

A systems programming language that runs blazingly fast, prevents segfaults, and guarantees memory safety without garbage collection.

Memory Safe Zero-Cost Abstractions Systems Programming

What is Rust?

Rust is a systems programming language focused on safety, speed, and concurrency. It eliminates memory bugs at compile time without garbage collection.

hello, rust!
fn main() {
    println!("Hello, Rust!");
}

// Variables are immutable by default
let x = 5;        // immutable
let mut y = 10;   // mutable
y += 5;

⚡ Performance

No runtime or garbage collector. Rust compiles to native code, as fast as C/C++.

🛡️ Memory Safety

Ownership system prevents null pointers, buffer overflows, and data races at compile time.

📦 Cargo

Built-in package manager and build system — one of the best in any language.

Ownership

Ownership is Rust's most unique feature. Every value has a single owner, and when the owner goes out of scope, the value is dropped.

ownership rules
fn main() {
    let s1 = String::from("hello");
    let s2 = s1;  // s1 is MOVED, no longer valid
    // println!("{}", s1); ❌ compile error
    println!("{}", s2);
}

// To copy, use clone()
let s1 = String::from("hello");
let s2 = s1.clone();
println!("{} {}", s1, s2);  // works

Borrowing & References

Instead of transferring ownership, you can borrow values using references. References allow you to use data without taking ownership.

borrowing
fn main() {
    let s = String::from("hello");
    calculate_length(&s);  // immutable borrow
    println!("{}", s);     // still valid
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

// Mutable reference
fn change(s: &mut String) {
    s.push_str(", world");
}
💡 Rule: You can have either one mutable reference OR any number of immutable references, but never both at the same time.

Structs & Enums

Structs let you create custom data types. Enums allow you to define types with variants — especially powerful with Option and Result.

structs
struct User {
    username: String,
    email: String,
    active: bool,
}

let user1 = User {
    email: String::from("alice@example.com"),
    username: String::from("alice"),
    active: true,
};
enums & option
enum IpAddrKind {
    V4(String),
    V6(String),
}

// Option<T> — no more null pointers!
let some_number = Some(5);
let absent_number: Option<i32> = None;

match some_number {
    Some(x) => println!("Value: {}", x),
    None => println!("No value"),
}

Pattern Matching

Match is like a supercharged switch statement. It's exhaustive — you must handle all possible cases.

match expression
enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter => 25,
    }
}

// if let for single case
if let Some(x) = some_number {
    println!("x is {}", x);
}

Error Handling

Rust has two categories of errors: recoverable (Result<T,E>) and unrecoverable (panic!).

result type
use std::fs::File;

fn main() {
    let greeting_file = File::open("hello.txt");

    let file = match greeting_file {
        Ok(file) => file,
        Err(error) => panic!("Problem opening file: {:?}", error),
    };
}

// Propagate errors with ? operator
fn read_username() -> Result<String, io::Error> {
    let mut file = File::open("username.txt")?;
    let mut name = String::new();
    file.read_to_string(&mut name)?;
    Ok(name)
}

Fearless Concurrency

Rust's ownership system catches data races at compile time. Threads, channels, and shared state are all memory-safe.

threads
use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("thread: {}", i);
            thread::sleep(Duration::from_millis(100));
        }
    });

    for i in 1..5 {
        println!("main: {}", i);
        thread::sleep(Duration::from_millis(50));
    }
    handle.join().unwrap();
}

Cargo & Crates

Cargo is Rust's build system and package manager. Create new projects, add dependencies, and run tests with simple commands.

cargo commands
# Create a new project
cargo new my_project
# Build the project
cargo build
# Build and run
cargo run
# Run tests
cargo test
# Add a dependency
cargo add serde
cargo.toml example
[package]
name = "my_project"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }

🛠 Project: CLI Grep Tool

Build a simple command-line tool that searches for text in files — similar to grep. This project covers file I/O, error handling, and command-line arguments.

src/main.rs
use std::env;
use std::fs;
use std::process;

fn main() {
    let args: Vec<String> = env::args().collect();

    let config = Config::build(&args).unwrap_or_else(|err| {
        eprintln!("Problem parsing arguments: {}", err);
        process::exit(1);
    });

    if let Err(e) = run(config) {
        eprintln!("Application error: {}", e);
        process::exit(1);
    }
}

fn run(config: Config) -> Result<(), Box<dyn std::error::Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    for line in contents.lines() {
        if line.contains(&config.query) {
            println!("{}", line);
        }
    }
    Ok(())
}

struct Config {
    query: String,
    file_path: String,
}

impl Config {
    fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough arguments");
        }
        let query = args[1].clone();
        let file_path = args[2].clone();
        Ok(Config { query, file_path })
    }
}
🎯 Challenge: Add case-insensitive search with an environment variable. Use `std::env::var` to check for IGNORE_CASE.