Back to posts

Getting Started with Rust

A practical introduction to Rust's ownership model and why it's becoming the go-to language for systems programming.

rustprogrammingsystems

A wolf in nature
A wolf in nature

Rust has become one of my favorite languages for building reliable software. Its unique approach to memory safety—without a garbage collector—makes it ideal for performance-critical applications.

Why Rust?

Rust offers safety, speed, and concurrency without compromise. Unlike C or C++, it prevents common bugs like null pointer dereferences and data races at compile time.

Here's Rust's ownership system in action:

rust
fn main() {
    let s1 = String::from("hello");
    let s2 = s1; // s1 is moved to s2
    
    // This would fail to compile:
    // println!("{}", s1);
    
    println!("{}", s2); // Works fine
}

The compiler catches the error before your code ever runs.

Error Handling

Rust's Result type makes error handling explicit:

rust
use std::fs::File;
use std::io::{self, Read};

fn read_file(path: &str) -> Result<String, io::Error> {
    let mut file = File::open(path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents)
}

fn main() {
    match read_file("config.toml") {
        Ok(data) => println!("Config: {}", data),
        Err(e) => eprintln!("Error: {}", e),
    }
}

The ? operator propagates errors cleanly without try-catch blocks.

Pattern Matching

One of Rust's most powerful features:

rust
enum Status {
    Active,
    Inactive,
    Pending { reason: String },
}

fn handle_status(status: Status) {
    match status {
        Status::Active => println!("System is active"),
        Status::Inactive => println!("System is offline"),
        Status::Pending { reason } => println!("Pending: {}", reason),
    }
}

The compiler ensures you handle every case.

Getting Started

Install via rustup:

bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Create a project:

bash
cargo new my_project
cd my_project
cargo run

The learning curve is real, but the payoff is code that's both fast and reliable.