Skip to content
Shop

Rust

Rust is a general-purpose programming language emphasizing performance, type safety, and concurrency. It enforces memory safety, meaning that all references point to valid memory, without a garbage collector.

Getting Started

Like Java, the main function is the entry point of a rust program. Rust files are written in .rs files and must contain a main function.

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

Rust must be compiled first and then ran. Use the rustc command followed by the name of the file to run the rust program.

bash
rustc main.rs && ./main

On windows:

bash
rustc main.rs
.\main.exe

Comments

rust
// hello, world
rust
// So we’re doing something complicated here, long enough that we need
// multiple lines of comments to do it! Whew! Hopefully, this comment will
// explain what’s going on.

Data Types & Data Structures

LengthSignedUnsigned
8-biti8u8
16-biti16u16
32-biti32u32
64-biti64u64
128-biti128u128
archisizeusize

Compound Types

rust
fn main() {
    let tup: (i32, f64, u8) = (500, 6.4, 1);

    let x: i32 = 10; //32 bit integer

    let tup = (500, 6.4, 1);
    let (x, y, z) = tup;
    println!("The value of y is: {y}");
}
rust
fn main() {
    let a = [1, 2, 3, 4, 5];
    let a: [i32; 5] = [1, 2, 3, 4, 5];
}

Learn more about Types

Arrays

Variables

Rust variables are immutable by default which means you can't change them unless you specifically allow them to be changed.

rust
fn main() {
    let x = 5;
    println!("The value of x is: {x}");
    x = 6;
    println!("The value of x is: {x}");
}

To make a variable mutable(changeable) add the mut keyword before the variable name.

rust
fn main() {
    let mut x = 5;
    println!("The value of x is: {x}");
    x = 6;
    println!("The value of x is: {x}");
}
rust
fn main() {
    const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
}

Learn more about Variables

Statements

let

expression

Learn more about Statements

Control Flow

rust
fn main() {
    let number = 3;

    if number < 5 {
        println!("condition was true");
    } else {
        println!("condition was false");
    }
}

Learn more about Control Flow

Error Handling (Panic)

rust
fn main() {
    panic!("crash and burn");
}

Learn more about Error Handling

Loops

For Loop

rust
fn main() {
    let v = &["apples", "cake", "coffee"];

    for text in v {
        println!("I like {}.", text);
    }
}
rust
fn main() {
    let mut sum = 0;
    for n in 1..11 {
        sum += n;
    }
    assert_eq!(sum, 55);
}
rust
fn main() {
    'a: loop {
        'a: loop {
            break 'a;
        }
        print!("outer loop");
        break 'a;
    }
}
rust
let result = 'block: {
    do_thing();
    if condition_not_met() {
        break 'block 1;
    }
    do_next_thing();
    if condition_not_met() {
        break 'block 2;
    }
    do_last_thing();
    3
};

Predicate Loop

rust
fn main(){
    let mut i = 0;
    while i < 10 {
        println!("hello");
        i = i + 1;
    }
}

Learn more about Loops

Functions

rust
fn main() {
    println!("Hello, world!");

    another_function();
}

fn another_function() {
    println!("Another function.");
}
rust
fn main() {
    print_labeled_measurement(5, 'h');
}

fn print_labeled_measurement(value: i32, unit_label: char) {
    println!("The measurement is: {value}{unit_label}");
}

There is no return keyword in rust. The last line of the function is the returned so long as it doesn't contain a semicolon

rust
fn five() -> i32 {
    5
}

fn main() {
    let x = five();

    println!("The value of x is: {x}");
}

fn sum(a: i32, b: i32){
    a + b
}

Learn more about Functions

Structs

rust
fn main(){
    struct Point {x: i32, y: i32}
    let p = Point {x: 10, y: 11};
    let px: i32 = p.x;
}
rust
fn main(){
    struct Cookie;
    let c = [Cookie, Cookie {}, Cookie, Cookie {}];
}

Learn more about Structs

Ownership & Borrowing

Values can be borrowed using the & sign.

rust
fn main(){
    let s1 = String::from("hello");
    let len = calculate_length(&s1); // borrowing

    println!("Length of {} is {}", s1,len);
}

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

You can read s: &String as "s" is a borrowed string.

Lifetimes

Pattern Matching

_ is a default or catch-all clause.

rust
fn main(){
    let number = 7;
    match number{
        1 => println!("one"),
        2 => println!("one"),
        3 | 4 | 5 => println!("Three, Four, Five"),
        6..=10 => println!("Between six and ten"),
        _ => println!("Anything else"),
    }
}

Error Handling

Rust makes sure you handle errors

rust
fn divide(){
    if b == 0 {
        Err(String::from("Division by zero"))
    }else{
        Ok(a/b)
    }
}

Libraries

mod modules, use paths, pub public (private by default). mod is like the class keyword of Python. You can have modules in modules like ruby.

rust
pub mod network{
    fn connect(){
        println!("Connection established");
    }

    pub fn initiate_connection(){
        connect();
        println("Initiating connection.")
    }
}
fn main(){
    network::initiate_connection();
}
rust
fn main(){

}
rust
fn main(){

}

Package Management with Cargo

To check the Cargo version

bash
cargo --version

To create a new project

bash
cargo new hello_cargo
cd hello_cargo

Build the project

bash
cargo build

To run the project

bash
cargo run

Learn more about Cargo

Useful Snippets

rust
// Get filenames
use std::fs;

fn main() {
    let paths = fs::read_dir("./").unwrap();

    for path in paths {
        println!("Name: {}", path.unwrap().path().display())
    }
}
rust
use std::fs;
use std::path::PathBuf;

fn main() {
    let dir_path = PathBuf::from("./"); // replace with your desired directory path
    let file_name = "new_file.txt";

    let file_path = dir_path.join(file_name);
    fs::create_dir_all(&dir_path).expect("Failed to create directory");
    fs::write(&file_path, "").expect("Failed to write file");

    println!("File created successfully: {}", file_path.display());
}
rust
use std::fs;
use std::path::PathBuf;

fn main() {
    let dir_path = PathBuf::from("./"); // replace with your desired directory path
    let file_name = "new_file.txt";

    let file_path = dir_path.join(file_name);
    fs::create_dir_all(&dir_path).expect("Failed to create directory");

    if file_path.exists() {
        fs::remove_file(&file_path).expect("Failed to delete file");
        println!("File deleted successfully: {}", file_path.display());
    } else {
        println!("File not found: {}", file_path.display());
    }
}

Resources