Introduction to Rust & Setup
What is Rust?
Rust is a modern systems programming language focused on performance, memory safety, and thread safety without a garbage collector. It is loved by developers for its powerful ownership system that prevents many bugs at compile time.
Why Rust?
- Zero-cost abstractions
- Memory safety without garbage collection
- Excellent concurrency support
- Growing ecosystem (web, CLI, embedded, WASM)
Installation
Use rustup โ the official Rust toolchain installer.
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh rustc --version cargo --version
Your First Rust Program
fn main() { println!("Hello, Rust Mastery!"); println!("Welcome to safe systems programming!"); }
Welcome to safe systems programming!
Run cargo new hello_rust, then modify src/main.rs to print your name and compile/run it with cargo run.
Variables & Ownership
Immutability by Default
In Rust, variables are immutable by default. Use mut to make them mutable.
let x = 5; // x = 6; // Error! let mut y = 10; y = 11; // OK
Introduction to Ownership
Each value in Rust has a variable that's called its owner. When the owner goes out of scope, the value is dropped.
Data Types & Functions
Scalar & Compound Types
- Integers: i32, u32, i64, etc.
- Floating-point: f32, f64
- Boolean: bool
- Tuple: (i32, f64, u8)
Control Flow
If Expressions
let condition = true; let number = if condition { 5 } else { 6 };
Loops & Iterators
Looping with 'for'
for i in 1..=5 { println!("{}", i); }
Ownership & Borrowing
References & Borrowing
Instead of transferring ownership, you can "borrow" a value using references (&).
fn calculate_length(s: &String) -> usize { s.len() }
Structs & Enums
Pattern Matching
match some_option { Some(i) => println!("{}", i), None => println!("None"), }
Collections & Strings
Vectors (Dynamic Arrays)
let mut v = vec![1, 2, 3]; v.push(4);
Error Handling
Panic vs Result
Rust groups errors into two categories: recoverable (Result<T, E>) and unrecoverable (panic!).
Modules & Crates
Cargo is Rust's build system and package manager. Use Cargo.toml to manage dependencies.
Traits & Generics
Defining Shared Behavior
pub trait Summary { fn summarize(&self) -> String; }
Capstone Project: Secure CLI
Create a Command Line Interface (CLI) tool that securely manages passwords or encrypts files using crates like clap and rust-crypto.
// Project goals: // 1. Parse CLI arguments // 2. Handle file I/O safely // 3. Implement robust error handling // 4. Use traits for polymorphic output