Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Programming in Rust

Rust is a systems programming language designed for building high-performance and robust software. It is a compiled language that is roughly similar in role as C/C++, but incorporates modern semantics and has an emphasis on enforcing safe coding practices. For these reasons, it is our language of choice for the low-level Project Elara libraries, including Elara Math, our scientific computing library, and Elara GFX, our graphics and visualization library.

// Hello world in Rust
fn main() {
    println!("Hello, world!");
}

Installing Rust

To get started with Rust, the recommended official installation method is Rustup. Simply click on the link to go to the website and follow the instructions there. It should get you set up with all the development tools required for writing Rust!

Learning Rust

Our recommended way to learn Rust is Rustlings. These are a set of interactive Rust tutorials that teach you the most important concepts around the Rust language. Starting from zero Rust knowledge, it can help you get started programming real Rust code in about a week!

If you want to try out some Rust code but don’t want to set up a full Rust project, we recommend using the Rust playground. This is an interactive coding environment where you can write Rust code and have it run in-browser.

Finally, other excellent resources are available in learning Rust:

Basic Syntax

Variables

In Rust, variables are declared with the let keyword. By default, variables are immutable (once assigned, their value cannot be changed). To make a variable mutable, add the mut keyword.

let x = 5;          // immutable
let mut y = 10;     // mutable
y = 20;             // ok
// x = 6;           // error: cannot assign twice to immutable variable

Data Types

Rust is statically typed, meaning every variable type must be known at compile time. The compiler can usually infer the type, but it can also be written explicitly.

let a: i32 = -10;          // 32-bit signed integer
let b: u64 = 100;          // 64-bit unsigned integer
let c: f64 = 3.14;         // 64-bit float
let d: bool = true;        // boolean
let e: char = 'z';         // character
let f: &str = "hello";     // string slice

Control Flow

Rust uses if, else if, and else for conditional logic. Unlike many languages, if in Rust is an expression that can return a value.

let number = 7;

if number < 5 {
    println!("less than 5");
} else if number == 7 {
    println!("it's 7");
} else {
    println!("something else");
}

// if as an expression
let description = if number % 2 == 0 { "even" } else { "odd" };

Rust has three loop constructs: loop, while, and for.

// loop runs forever until a break
let mut count = 0;
loop {
    count += 1;
    if count == 3 {
        break;
    }
}

// while loop
let mut n = 0;
while n < 5 {
    n += 1;
}

// for loop over a range
for i in 0..5 {
    println!("{}", i);
}

Functions

Functions are declared with the fn keyword, followed by the function name, parameters, and return type. The return type is specified with ->. In Rust, the last expression in a function body is automatically returned.

fn add(a: i32, b: i32) -> i32 {
    a + b // returned implicitly
}

fn greet(name: &str) {
    println!("Hello, {}!", name);
}

fn main() {
    let result = add(3, 4);
    greet("Elara");
    println!("{}", result); // 7
}

Functions can also return early using the return keyword.

fn is_positive(n: i32) -> bool {
    if n <= 0 {
        return false;
    }
    true
}

Structs

Structs are used to group related data together into a single type. They are similar to classes in other languages, but without inheritance. A struct is defined with the struct keyword, and its fields are accessed with dot notation.

struct Point {
    x: f64,
    y: f64,
}

fn main() {
    let p = Point { x: 1.0, y: 2.5 };
    println!("x: {}, y: {}", p.x, p.y);
}

Methods are added to a struct using an impl block. The first parameter of a method is always &self, which refers to the instance the method is called on.

struct Rectangle {
    width: f64,
    height: f64,
}

impl Rectangle {
    fn area(&self) -> f64 {
        self.width * self.height
    }

    fn is_square(&self) -> bool {
        self.width == self.height
    }
}

fn main() {
    let rect = Rectangle { width: 4.0, height: 6.0 };
    println!("Area: {}", rect.area());
    println!("Is square: {}", rect.is_square());
}

impl blocks also contain associated functions. These functions don’t take &self and are called on the type itself. These are commonly used as constructors, typically named new.

impl Rectangle {
    fn new(width: f64, height: f64) -> Rectangle {
        Rectangle { width, height }
    }
}

fn main() {
    let rect = Rectangle::new(4.0, 6.0);
}

Enums

Enums allow defining a type that can be one of several variants. They are useful for representing a value that can be one of a possible set of values.

enum Direction {
    North,
    South,
    East,
    West,
}

fn main() {
    let dir = Direction::North;
}

Enum variants can also hold data.

enum Shape {
    Circle(f64),           // radius
    Rectangle(f64, f64),   // width, height
}

Enums are typically used with match, which lets you handle each variant separately. match must cover every variant.

fn describe(shape: Shape) {
    match shape {
        Shape::Circle(r) => println!("Circle with radius {}", r),
        Shape::Rectangle(w, h) => println!("Rectangle {}x{}", w, h),
    }
}

Arrays, Tuples, and Vecs

Arrays

Arrays store a fixed number of values of the same type. The size is part of the type and cannot change at runtime.

let arr: [i32; 4] = [1, 2, 3, 4];
println!("{}", arr[0]); // 1
println!("{}", arr.len()); // 4

Tuples

Tuples store a fixed number of values that can be of different types. Elements are accessed by index using dot notation.

let tup: (i32, f64, bool) = (42, 3.14, true);
println!("{}", tup.0); // 42
println!("{}", tup.1); // 3.14

// tuple values can also be destructured
let (x, y, z) = tup;
println!("{}", x); // 42

Vecs

A Vec (vector) stores a growable list of elements of the same type. Unlike arrays, its size can change at runtime.

let mut v: Vec<i32> = Vec::new();
v.push(1);
v.push(2);
v.push(3);
println!("{}", v[0]); // 1
println!("{}", v.len()); // 3

// vecs can also be created with the vec! macro
let v2 = vec![10, 20, 30];

for loops are used to iterate over a Vec:

for val in &v2 {
    println!("{}", val); 
}

Ownership and borrowing

Ownership is a set of rules the compiler uses to manage memory in Rust. It generally allows the compiler to guarantee memory safety. Every value has a single owner at a time; it frees when the owner goes out of scope.

Ownership and moves

When a value is assigned to another variable, the ownership is moved. The original variable is no longer used.

let s1 = String::from("hello");
let s2 = s1; // ownership moves to s2
// println!("{}", s1); // error: s1 is no longer valid
println!("{}", s2); // ok

Simple types, such as integers and chars, implement the Copy trait, so they are copied instead of moved.

let x = 5;
let y = x; // x is copied
println!("{}", x); // ok

Borrowing

To use a value without taking ownership, Rust allows borrowing with references. A reference is created with & and doesn’t take ownership of a value.

fn print_length(s: &String) {
    println!("Length: {}", s.len());
}

fn main() {
    let s = String::from("hello");
    print_length(&s); // borrow s
    println!("{}", s); // ok
}

Mutable references

References are immutable. To allow a function to change a borrowed value, use a mutable reference with &mut.

fn add_exclamation(s: &mut String) {
    s.push_str("!");
}

fn main() {
    let mut s = String::from("hello");
    add_exclamation(&mut s);
    println!("{}", s); // hello!
}

Rust enforces these rules at compile time using a borrow checker. This ensures that references don’t outlive the data they point to and that mutable and immutable references never coexist.

Error Handling

Rust does not use exceptions for error handling. It uses two built-in enums: Option and Result. Rust groups errors into two categories: recoverable errors and unrecoverable errors.

Option

Option represents a value that may or may not exist. It has two variants: Some(value) when a value exists, and None when it doesn’t.

fn find_first_even(numbers: &[i32]) -> Option<i32> {
    for &n in numbers {
        if n % 2 == 0 {
            return Some(n);
        }
    }
    None
}

fn main() {
    let nums = vec![1, 3, 4, 7];
    match find_first_even(&nums) {
        Some(n) => println!("Found: {}", n),
        None => println!("No even number found"),
    }
}

Result

Result represents an operation that can either succeed or fail. It has two variants: Ok(value) on success and Err(error) on failure.

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

fn main() {
    match divide(10.0, 2.0) {
        Ok(result) => println!("Result: {}", result),
        Err(e) => println!("Error: {}", e),
    }
}

The ? operator

The ? operator is a shorthand for propagating errors. When used inside a function that returns Result, it returns the error early if there is one or unwraps the value.

use std::fs;

fn read_file(path: &str) -> Result<String, std::io::Error> {
    let contents = fs::read_to_string(path)?;
    Ok(contents)
}

Unrecoverable errors

Rust provides the panic! macro for errors that should never happen or indicate a bug. This immediately prints an error message and quits the program.

fn get_first(v: &[i32]) -> i32 {
    if v.is_empty() {
        panic!("vector is empty!");
    }
    v[0]
}

Generics

Generics allow writing code that works with multiple types without duplicating the implementation. A generic type parameter is written in angle brackets, usually named T.

fn largest<T: PartialOrd>(a: T, b: T) -> T {
    if a > b { a } else { b }
}

fn main() {
    println!("{}", largest(3, 7));       // 7
    println!("{}", largest(1.5, 0.8));   // 1.5
}

The T: PartialOrd part is a trait bound. It constrains T to only types that support comparison.

Structs can also be generic:

struct Pair<T> {
    first: T,
    second: T,
}

impl<T> Pair<T> {
    fn new(first: T, second: T) -> Pair<T> {
        Pair { first, second }
    }
}

Generics are used extensively in the Elara codebase. In elara-gfx-community, buffer data methods accept a generic type T so they can work with any numeric data:

pub fn data<T>(&self, buffer_type: BufferType, data: &[T], usage: types::GLenum) {
    // ...
}

This allows the same function to be used with f32, u32, or any other type.

Macros

Macros are a way to let code write other code. They are identified by a ! at the end of their name. Rust has declarative macros and procedural macros. This section covers declarative macros, which are the most common form.

A macro is defined with macro_rules! and uses pattern matching to transform input into output:

macro_rules! say_hello {
    () => {
        println!("Hello!");
    };
    ($name:expr) => {
        println!("Hello, {}!", $name);
    };
}

fn main() {
    say_hello!();           // Hello!
    say_hello!("Elara");    // Hello, Elara!
}

Macros are useful for reducing repetitive code. In elara-math-community, the tensor! and scalar! macros allow tensors to be created quickly each time:

// Without macros
let t = Tensor::new(ndarray::array!([[1.0, 2.0], [3.0, 4.0]]));

// With the tensor! macro
let t = tensor![[1.0, 2.0], [3.0, 4.0]];

// Creating a scalar tensor
let s = scalar!(3.14);

In elara-math-community, the impl_binary_op! macro automatically generates operator implementations (+, -, etc.) for Tensor. This allows each operator to be generated from a single pattern instead of separately.

Common built-in Rust macros:

Pointers

Rust has several smart pointer types that provide different ownership and borrowing behaviors.

Box

Box<T> allocates a value on the heap instead of the stack. It’s useful when the size of a value isn’t known at compile time, or when you want to transfer ownership of a large value without copying it.

let x = Box::new(5);
println!("{}", x); // 5

Rc

Rc<T> allows multiple owners of the same value. The value is freed when the last owner is dropped. Rc is useful when a value needs to be shared across different parts of a program.

use std::rc::Rc;

let a = Rc::new(String::from("hello"));
let b = Rc::clone(&a);

println!("{}", a); // hello
println!("{}", b); // hello

RefCell

RefCell<T> allows mutating a value even with multiple references to it. It moves borrow checking from compile time to runtime. It is usually paired with Rc to allow for shared, mutable ownership.

In elara-math-community, the Tensor type uses Rc<RefCell<TensorData>>:

pub struct Tensor(Rc<RefCell<TensorData>>);

This allows multiple parts of the graph to hold a reference to the same tensor and mutate its data without violating ownership rules.

Design Patterns and API Design

As you become more comfortable with Rust, it is worth learning common patterns and conventions used in Rust. Two great resources for this are: