← Back to Index

Rust Reference

0. Basics

0.1 Hello World

Standard entry point and output.

fn main() {
    // println! is a macro for printing to STDOUT with a newline
    println!("Hello, World!");
}
TERMINAL OUTPUT
Hello, World!

0.2 Building & Running

Commands to compile and execute.

# Compile to a standalone binary using rustc
rustc main.rs

# Run the generated binary
./main
TERMINAL OUTPUT
Hello, World!

0.3 Comments

Annotating code for humans.

fn main() {
    // Single-line comment for brief notes
    
    /* Multi-line
       comment block for detailed explanations */
    
    /// Doc comment for items (functions, structs) that appear in rustdoc
    //! Doc comment for modules/files that appear in rustdoc
}
TERMINAL OUTPUT
(No output)

0.4 Imports

Bringing external modules into scope.

// use keyword brings paths into scope
use std::io;
use std::fs::{self, File}; // Nested imports for multiple items from one module
use std::collections as coll; // Aliasing for shorter or more descriptive names
TERMINAL OUTPUT
(No output)

0.5 Exit Codes

Terminating the process with a status.

use std::process;

fn main() {
    // exit(0) for success, non-zero for error (e.g., 1)
    process::exit(1); 
}
TERMINAL OUTPUT
(Process exits with status 1)

0.6 Error Handling

Propagating and handling optional or error values.

// Result<T, E> for recoverable errors, Option<T> for presence/absence
fn divide(a: f64, b: f64) -> Result<f64, String> {
    // Return Error if divisor is zero
    if b == 0.0 { return Err("Div by zero".into()); }
    Ok(a / b) // Return wrapped success value
}

fn main() -> Result<(), String> {
    // The ? operator unwraps Ok or returns Err immediately
    let val = divide(10.0, 2.0)?; 
    
    // match for explicit handling of Option variants
    match Some(42) {
        Some(v) => println!("Got {}", v), // Print if value exists
        None => (), // Do nothing if value is absent
    }
    Ok(()) // Return success for main
}
TERMINAL OUTPUT
Got 42

1. Environment, Variables & Time

1.1 Variable Declaration

Mutable vs Immutable state.

fn main() {
    let x = 5; // Immutable (default) - cannot be changed
    let mut y = 10; // Mutable - can be updated later
    const MAX: u32 = 100; // Constant - must have type, evaluated at compile-time
    y = 15; // Updating mutable variable
}
TERMINAL OUTPUT
(No output)

1.2 Integer Types & Limits

Architectural and fixed-size integers.

Size Signed Unsigned
8-bit i8 u8
32-bit i32 u32
Arch isize usize

Limits: i32::MAX, u64::MIN.

1.3 Casting

Explicit type conversion.

fn main() {
    let f: f64 = 3.14; // Float
    let i: i32 = f as i32; // Explicit truncation to integer
    let c: char = 65u8 as char; // Byte 'A' cast to character
}
TERMINAL OUTPUT
(No output)

1.4 Environment Variables

Accessing system configuration.

use std::env;

fn main() {
    // Get variable by name (returns Result)
    let path = env::var("PATH").unwrap();
    
    // Set variable for the current process scope
    env::set_var("APP_KEY", "secret");
}
TERMINAL OUTPUT
(No output)

1.5 Time Measurement & Formatting

High-resolution timing and string representation.

use std::time::{Instant, SystemTime, UNIX_EPOCH};

fn main() {
    // High-resolution measurement for duration
    let start = Instant::now();
    let elapsed = start.elapsed(); 
    
    // Formatting SystemTime as raw epoch seconds
    let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    println!("Seconds: {}", now.as_secs());
}
TERMINAL OUTPUT
Seconds: 1715856000 (example)

2. Operators & Regex

2.1 Arithmetic & Logic

Core mathematical and boolean operations.

fn main() {
    let a = 10 + 3; // Addition (13)
    let b = 10 / 3; // Integer division (3)
    let c = 10.0 / 3.0; // Floating point division (3.33)
    let d = true && false; // Logical AND (false)
}
TERMINAL OUTPUT
(No output)

2.2 Regex & Pattern Matching

Rust std does NOT have regex; use str methods for basic patterns.

fn main() {
    let s = "user@example.com";
    
    // Check if string contains character
    let has_at = s.contains('@');
    // Split string into vector of slices
    let parts: Vec<&str> = s.split('@').collect();
    // Check string suffix
    let is_email = s.ends_with(".com");
}
TERMINAL OUTPUT
(No output)

3. Argument Parsing

3.1 Argument Parsing

Handling flags, optional, and mandatory arguments.

use std::env;

fn main() {
    // Collect all CLI arguments into a Vector
    let args: Vec<String> = env::args().collect();
    
    let mut file = None;
    let mut verbose = false;
    
    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "-f" => { file = Some(&args[i+1]); i += 1; } // Flag with value
            "-v" => { verbose = true; } // Boolean flag
            _ => { /* positional args */ }
        }
        i += 1;
    }
}
TERMINAL OUTPUT
(No output)

4. Functions & Memory

4.1 Declaration & Returns

Defining reusable logic and return types.

// Basic function with integer return
fn add(a: i32, b: i32) -> i32 { a + b }

// Multi-return function via Tuple
fn swap(a: i32, b: i32) -> (i32, i32) { (b, a) }
TERMINAL OUTPUT
(No output)

4.2 References & Pointers

Borrowing and dereferencing data.

// Pass by immutable reference (&)
fn print_len(s: &String) { println!("{}", s.len()); }

// Pass by mutable reference (&mut)
fn increment(n: &mut i32) {
    *n += 1; // Explicit dereference (*) to modify original value
}

fn main() {
    let mut val = 10;
    increment(&mut val); // Pass mutable reference
}
TERMINAL OUTPUT
(No output)

5. Control Flow

5.1 Conditionals (If/Else)

Standard branching logic. Rust has no implicit truthiness; conditions must be bool.

fn main() {
    let x = 10;
    if x > 5 {
        println!("Greater");
    } else if x == 5 {
        println!("Equal");
    } else {
        println!("Less");
    }
}
TERMINAL OUTPUT
Greater

5.2 Switch / Case

Pattern matching via the match keyword.

fn main() {
    let val = 2;
    match val {
        1 => println!("One"),
        2 | 3 => println!("Two or Three"),
        _ => println!("Other"),
    }
}
TERMINAL OUTPUT
Two or Three

5.3 Basic Loops (While/For)

Conditional and range-based iteration.

fn main() {
    let mut i = 0;
    while i < 3 {
        println!("while: {}", i);
        i += 1;
    }
    for j in 0..3 {
        println!("for: {}", j);
    }
}
TERMINAL OUTPUT
while: 0
while: 1
while: 2
for: 0
for: 1
for: 2

5.4 Breaking & Continue

Controlling loop execution.

fn main() {
    for i in 0..10 {
        if i < 2 { continue; } // Skip to next iteration
        if i == 5 { break; }    // Exit loop
        println!("{}", i);
    }
}
TERMINAL OUTPUT
2
3
4

5.5 Iterating Collections

Accessing elements in a collection.

fn main() {
    let v = vec![10, 20];
    // Iterating over collection by immutable reference
    for x in &v {
        println!("{}", x);
    }
}
TERMINAL OUTPUT
10
20

6. Strings & Files

6.1 String Manipulation

fn main() {
    let mut s = String::from("Hello"); // Heap-allocated string
    s.push_str(" World"); // Append string slice
    let sub = &s[0..5]; // Create string slice
    let joined = vec!["a", "b"].join("-"); // Join vector into string "a-b"
}
TERMINAL OUTPUT
(No output)

6.2 Path Joining

use std::path::PathBuf;

fn main() {
    // OS-agnostic path building
    let mut p = PathBuf::from("/");
    p.push("usr");
    p.push("bin"); // Result: "/usr/bin"
}
TERMINAL OUTPUT
(No output)

6.3 Streaming I/O (Chunks)

Reading/Writing large files without loading all at once.

use std::io::{Read, Write};
use std::fs::File;

fn main() -> std::io::Result<()> {
    // Open file for reading
    let mut f = File::open("large.bin")?;
    let mut buffer = [0; 4096]; // Fixed-size 4KB buffer
    loop {
        let n = f.read(&mut buffer)?; // Read into buffer
        if n == 0 { break; } // End of file
        // Process n bytes in buffer
    }
    Ok(())
}
TERMINAL OUTPUT
(No output)

6.4 Read to Memory

Loading entire file into a Vec or String.

use std::fs;

fn main() -> std::io::Result<()> {
    // Read entire file as bytes
    let bytes = fs::read("file.bin")?;
    // Read entire file as UTF-8 string
    let s = fs::read_to_string("file.txt")?;
    Ok(())
}
TERMINAL OUTPUT
(No output)

7. Binary & Bitwise

7.1 Allocation & Packing

Creating buffers and packing Big-Endian data.

fn main() {
    // Allocate mutable buffer with zeros
    let mut buf = vec![0u8; 12];
    
    // Convert i32 to Big-Endian bytes and copy into slice
    let val: i32 = 42;
    buf[0..4].copy_from_slice(&val.to_be_bytes());
}
TERMINAL OUTPUT
(No output)

7.2 Bitwise Operations

Low-level bit manipulation.

fn main() {
    let res = 0b1010 & 0b1100; // Bitwise AND
    let res = 0b1010 | 0b1100; // Bitwise OR
    let res = 0b1010 ^ 0b1100; // Bitwise XOR
    let res = !0b1010; // Bitwise NOT
    let res = 0b0001 << 2; // Shift Left (0b0100)
}
TERMINAL OUTPUT
(No output)

7.3 Hex Conversion

fn main() {
    // Format integer as hex string
    let s = format!("{:x}", 255); // "ff"
    // Parse hex string back to integer
    let val = i64::from_str_radix("ff", 16).unwrap(); // 255
}
TERMINAL OUTPUT
(No output)

8. Collections & JSON

8.1 Lists, Maps & Sets

Core data structures.

use std::collections::{HashMap, HashSet};

fn main() {
    // Vector (Dynamic List)
    let mut v = vec![1, 2]; v.push(3); 
    // HashMap (Key-Value)
    let mut m = HashMap::new(); m.insert("k", "v"); 
    // HashSet (Unique values)
    let mut s = HashSet::new(); s.insert(1); 
}
TERMINAL OUTPUT
(No output)

8.2 JSON Parsing

Rust Std has NO JSON support. Use string manipulation for simple keys.

fn main() {
    let json = r#"{"id": 42}"#;
    // Manual slice for simple key extraction from JSON string
    let id = json.split(':').last().unwrap().trim_matches(|c| c == ' ' || c == '}');
    println!("ID: {}", id);
}
TERMINAL OUTPUT
ID: 42

9. Systems & Networking

9.1 TCP Server & Client

Raw socket communication.

use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};

fn main() -> std::io::Result<()> {
    // Bind TCP listener to local address
    let listener = TcpListener::bind("127.0.0.1:8080")?;
    
    // Connect to external host via TCP
    let mut stream = TcpStream::connect("example.com:80")?;
    // Send raw bytes to stream
    stream.write_all(b"GET / HTTP/1.0\r\n\r\n")?;
    Ok(())
}
TERMINAL OUTPUT
(No output)

9.2 UDP Server & Client

Datagram communication.

use std::net::UdpSocket;

fn main() -> std::io::Result<()> {
    // Bind UDP socket to local port
    let socket = UdpSocket::bind("127.0.0.1:0")?;
    // Send datagram to target address
    socket.send_to(b"ping", "127.0.0.1:8080")?;
    Ok(())
}
TERMINAL OUTPUT
(No output)

9.3 Concurrency

Spawning threads.

use std::thread;

fn main() {
    // Spawn a new OS thread
    let handle = thread::spawn(|| {
        println!("Background task");
    });
    // Wait for thread to finish
    handle.join().unwrap();
}
TERMINAL OUTPUT
Background task

9.4 SQLite

CLI Bridge for persistence.

use std::process::Command;

fn main() {
    // Invoke sqlite3 CLI via system command
    let out = Command::new("sqlite3")
        .arg(":memory:")
        .arg("SELECT 42;")
        .output().unwrap();
    // Print STDOUT from process
    println!("{}", String::from_utf8_lossy(&out.stdout));
}
TERMINAL OUTPUT
42