Rust Programming

Rust is a blazingly fast and memory-efficient language with no runtime or garbage collector. It empowers developers to build reliable and efficient software with zero-cost abstractions.

Why Learn Rust?

  • Memory safety without garbage collection
  • Blazingly fast performance
  • Fearless concurrency
  • Rich type system and ownership model
  • Most loved programming language (Stack Overflow survey)

Getting Started with Rust

Rust is a multi-paradigm programming language focused on performance and safety, especially safe concurrency. Rust is syntactically similar to C++, but provides memory safety without using garbage collection.

Installing Rust

Install Rust using rustup, the Rust toolchain installer:

On Linux/macOS

# In your terminal
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

On Windows

# Download and run rustup-init.exe
# from https://rustup.rs

Verify Installation

rustc --version
cargo --version

First Program

Create a simple Rust program with Cargo:

// Create a new project
cargo new hello_world
cd hello_world

// Edit src/main.rs
fn main() {
  println!("Hello, World!");
}

Run the program:

cargo run
# Output: Hello, World!

Rust Basics

Variables & Mutability

// Variables are immutable by default
let x = 5;
// x = 6; // Error!

// Mutable variables
let mut y = 5;
y = 6; // OK

// Constants
const MAX_POINTS: u32 = 100_000;

Data Types

// Scalar types
let a: i32 = 42; // integer
let b: f64 = 3.14; // float
let c: bool = true; // boolean
let d: char = '🦀'; // character

// Compound types
let tup: (i32, f64, u8) = (500, 6.4, 1);
let arr = [1, 2, 3, 4, 5];

Rust Topics

Comprehensive coverage of Rust programming concepts from beginner to advanced levels

Ownership & Borrowing

Understand Rust's unique ownership system that ensures memory safety without garbage collection.

// Ownership example
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2

// Borrowing example
let len = calculate_length(&s2);
println!("Length: {}", len);

Structs & Enums

Create custom data types with structs and enums, and implement methods.

// Struct example
struct User {
  username: String,
  email: String,
  sign_in_count: u64,
}

// Enum example
enum IpAddr {
  V4(u8, u8, u8, u8),
  V6(String),
}

Error Handling

Learn Rust's robust error handling with Result and Option types.

// Result type
fn divide(a: f64, b: f64) -> Result<f64, String> {
  if b == 0.0 {
    Err("Cannot divide by zero".to_string())
  } else {
    Ok(a / b)
  }
}

// Using ? operator
let result = divide(10.0, 2.0)?;

Generics & Traits

Write reusable code with generics and define shared behavior with traits.

// Generic function
fn largest<T: PartialOrd>(list: &[T]) -> &T {
  let mut largest = &list[0];
  for item in list {
    if item > largest {
      largest = item;
    }
  }
  largest
}

// Trait definition
trait Summary {
  fn summarize(&self) -> String;
}

Collections

Work with Rust's standard collection types: Vec, String, HashMap, etc.

// Vector example
let mut v: Vec<i32> = Vec::new();
v.push(1);
v.push(2);

// HashMap example
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert("Blue", 10);
scores.insert("Yellow", 50);

Concurrency

Write safe concurrent code with threads, message passing, and shared state.

// Thread example
use std::thread;

let handle = thread::spawn(|| {
  println!("Hello from a thread!");
});

handle.join().unwrap();

// Message passing
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();

Testing

Write unit and integration tests with Rust's built-in test framework.

// Unit test example
#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn it_works() {
    assert_eq!(2 + 2, 4);
  }

  #[test]
  #[should_panic]
  fn it_fails() {
    panic!("This test should fail");
  }
}

Async/Await

Write asynchronous code with Rust's async/await syntax.

// Async function
async fn fetch_data() -> Result<String, reqwest::Error> {
  let body = reqwest::get("https://example.com")
    .await?
    .text()
    .await?;
  Ok(body)
}

// Using tokio runtime
#[tokio::main]
async fn main() {
  let data = fetch_data().await.unwrap();
  println!("{}", data);
}

Macros

Create and use declarative and procedural macros.

// Declarative macro
macro_rules! vec {
  ( $( $x:expr ),* ) => {
    {
      let mut temp_vec = Vec::new();
      $( temp_vec.push($x); )*
      temp_vec
    }
  };
}

// Using the macro
let v: Vec<u32> = vec![1, 2, 3];

FFI (Foreign Function Interface)

Call C code from Rust and vice versa.

// Calling C from Rust
extern "C" {
  fn abs(input: i32) -> i32;
}

fn main() {
  unsafe {
    println!("Absolute value of -3: {}", abs(-3));
  }
}

// Calling Rust from C
#[no_mangle]
pub extern "C" fn rust_function() {
  println!("Hello from Rust!");
}

WebAssembly

Compile Rust to WebAssembly for high-performance web applications.

// Simple WASM example
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
  format!("Hello, {}!", name)
}

// Using in JavaScript
// import { greet } from './pkg/rust_wasm';
// console.log(greet('World'));

Web Frameworks

Build web applications with Rust frameworks like Actix and Rocket.

// Actix-web example
use actix_web::{web, App, HttpServer, Responder};

async fn index() -> impl Responder {
  "Hello from Actix!"
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
  HttpServer::new(|| {
    App::new().route("/", web::get().to(index))
  })
  .bind("127.0.0.1:8080")?
  .run()
  .await
}

Database Access

Connect to databases with Diesel and SQLx.

// Diesel ORM example
#[derive(Queryable)]
struct User {
  id: i32,
  name: String,
  email: String,
}

fn get_users(conn: &PgConnection) -> QueryResult<Vec<User>> {
  users::table.load(conn)
}

// SQLx async example
let row = sqlx::query!("SELECT * FROM users WHERE id = $1", 1)
  .fetch_one(&pool)
  .await?;

Unsafe Rust

Work with raw pointers and unsafe code when necessary.

// Unsafe example
let mut num = 5;

let r1 = &num as *const i32;
let r2 = &mut num as *mut i32;

unsafe {
  println!("r1 is: {}", *r1);
  *r2 = 10;
  println!("r1 is now: {}", *r1);
}

Embedded Development

Write firmware and bare-metal applications with Rust.

// Embedded Rust example
#![no_std]
#![no_main]

use panic_halt as _;
use arduino_hal::prelude::*;

#[arduino_hal::entry]
fn main() -> ! {
  let dp = arduino_hal::Peripherals::take().unwrap();
  let pins = arduino_hal::pins(dp);
  let mut led = pins.d13.into_output();

  loop {
    led.toggle();
    arduino_hal::delay_ms(1000);
  }
}

What Can You Build with Rust?

Rust's performance and safety guarantees make it suitable for a wide range of applications

Systems Programming

Build operating systems, device drivers, and other low-level software:

  • Operating systems (Redox OS)
  • File systems
  • Network stacks
// Simple OS example
#![no_std]
#![no_main]

use core::panic::PanicInfo;

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
  loop {}
}

#[no_mangle]
pub extern "C" fn _start() -> ! {
  loop {}
}

WebAssembly

Compile to WebAssembly for high-performance web apps:

  • Game engines
  • Image/video processing
  • Scientific computing
// WASM example with wasm-bindgen
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
  a + b
}

#[wasm_bindgen]
pub fn greet(name: &str) -> String {
  format!("Hello, {}!", name)
}

Networking Services

Build high-performance network services and servers:

  • Web servers (Actix, Rocket)
  • Database proxies
  • Load balancers
// Actix-web server
use actix_web::{get, web, App, HttpServer, Responder};

#[get("/{id}/{name}")]
async fn index(info: web::Path<(u32, String)>) -> impl Responder {
  format!("Hello {}! id:{}", info.1, info.0)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
  HttpServer::new(|| App::new().service(index))
  .bind("127.0.0.1:8080")?
  .run()
  .await
}

Command Line Tools

Build fast and reliable command-line applications:

  • System utilities
  • DevOps tools
  • Text processors
// CLI tool with clap
use clap::{App, Arg};

fn main() {
  let matches = App::new("My CLI Tool")
    .version("1.0")
    .author("Your Name")
    .about("Does awesome things")
    .arg(Arg::with_name("INPUT")
      .help("Sets the input file")
      .required(true)
      .index(1))
    .get_matches();

  println!("Input file: {}",
    matches.value_of("INPUT").unwrap());
}

Game Development

Build games with Rust game engines:

  • Bevy (Data-driven)
  • Amethyst (ECS-based)
  • ggez (Simple 2D)
// Bevy game example
use bevy::prelude::*;

fn main() {
  App::new()
    .add_plugins(DefaultPlugins)
    .add_startup_system(setup)
    .add_system(hello_world)
    .run();
}

fn setup(mut commands: Commands) {
  commands.spawn_bundle(OrthographicCameraBundle::new_2d());
}

fn hello_world() {
  println!("Hello, world!");
}

Blockchain & Cryptography

Build blockchain applications and cryptographic tools:

  • Cryptocurrencies
  • Smart contracts
  • Security tools
// Simple blockchain example
use sha2::{Sha256, Digest};

struct Block {
  index: u64,
  timestamp: i64,
  data: String,
  previous_hash: String,
  hash: String,
}

impl Block {
  fn calculate_hash(&self) -> String {
    let mut hasher = Sha256::new();
    hasher.update(format!("{}{}{}{}",
      self.index, self.timestamp, self.data, self.previous_hash));
    format!("{:x}", hasher.finalize())
  }
}

Rust Learning Path

A structured approach to mastering Rust programming

1 Beginner Level

  • Rust Syntax and Basics

    Variables, data types, functions, and control flow

  • Ownership & Borrowing

    Understand Rust's unique memory management system

  • Structs & Enums

    Create custom data types and implement methods

  • Error Handling

    Work with Result and Option types

2 Intermediate Level

  • Generics & Traits

    Write reusable code and define shared behavior

  • Collections

    Work with Vec, String, HashMap and other collections

  • Concurrency

    Threads, message passing, and shared state

  • Testing

    Write unit and integration tests

3 Advanced Level

  • Async/Await

    Write asynchronous code with async/await syntax

  • Macros

    Create and use declarative and procedural macros

  • FFI

    Call C code from Rust and vice versa

  • Unsafe Rust

    Work with raw pointers and unsafe code

Ready to Master Rust?

Join our Rust Mastery course and get access to interactive exercises, real-world projects, and expert support to accelerate your learning.