Crabrix blog

What is the Rust programming language? Compiled, no GC, memory-safe

What is the Rust programming language? A compiled language with no garbage collector and memory safety by default, with tested code and a first-week plan.

What is the Rust programming language?

What is the Rust programming language? In one sentence: Rust is a compiled, statically typed, general-purpose language without a garbage collector. Its compiler, rustc, checks types, ownership and borrowing before the program runs, and only a program that passes those checks becomes a native executable. That single design decision explains most of what people like about Rust, and most of what they find hard in the first weeks.

Rust suits software where speed, predictable memory use and correctness all matter: command-line tools, web servers, embedded devices, WebAssembly modules and parts of operating systems. Rust 1.0 was released in May 2015, and a new stable compiler has followed every six weeks since.

This guide follows the Crabrix Academy lesson What Rust Is and the Rust at a glance units of our bridge courses for C and Node.js developers. Every program below was compiled and run with rustc 1.99.0 on an Apple silicon Mac with --edition 2024, and the compiler error is real terminal output.

An orange paper crab beside a glowing forge that turns rolled source scrolls into a polished cyan block, with an idle garbage truck behind a no-entry sign
Original generated illustration: rustc as a forge that turns source into a native program, with no garbage collector waiting to clean up.

Sources: Announcing Rust 1.0 · The Rust Programming Language (the Book)

Explore in Crabrix: What Rust Is (Rust Basics, lesson 1) · Rust Basics course

Compiled ahead of time to native code and WebAssembly

Rust is compiled ahead of time. rustc, usually driven by Cargo, checks the whole crate and lowers it to LLVM IR; LLVM, the code generator family clang also uses, emits machine code for one target, and the linker produces an ordinary executable. The machine that runs it needs no interpreter, virtual machine or runtime package, because the standard library is linked into the binary.

Compare node app.js, which starts a runtime: V8 interprets the JavaScript and compiles hot functions while the program runs, and every machine needs Node.js installed. There, as in Python, calling a method that does not exist is discovered only when that line executes. In Rust, a type error in a branch your tests never reach still stops the build.

The target is a choice. rustc --edition 2024 targets.rs produced an arm64 Mach-O executable that printed area = 12 and compiled for aarch64. Adding --target wasm32-wasip1 produced a WebAssembly module from the same source, which printed area = 12 and compiled for wasm32 under Node.js's WASI support. That is the target Crabrix uses: the iPhone and iPad app and the browser Playground carry a real rustc and run your program on your device.

// rustc checks the whole file first, then writes a program for one target.
fn area(width: u32, height: u32) -> u32 {
    width * height
}

fn main() {
    let room = area(4, 3);
    println!("area = {room}");
    println!("compiled for {}", std::env::consts::ARCH);
}

Sources: rustc platform support · The wasm32-wasip1 target

Explore in Crabrix: Node.js runtime vs compiled Rust · What Rust Is, from C

Rust has no garbage collector: owners and Drop free memory

Rust has no garbage collector, and you do not call free either. Each value has exactly one owner, usually a variable. When the owner goes out of scope, the value is dropped: its Drop implementation runs, then its fields are dropped, then its memory is released. The compiler places that cleanup at a point you can see in the source, the closing brace of the owner's scope.

Ownership can move. Passing a Vec or String by value makes the function its new owner; returning it moves it back. A value is freed exactly once, by whoever owns it last. To release something early, call drop(value), an ordinary function that takes ownership and lets the value go.

Our run printed inner scope ends, then free temp (16 bytes) at the inner closing brace, free scratch (64 bytes) at the explicit drop, the last line of main, and finally free input (1024 bytes). Moving input through keep freed nothing, because ownership went in and came straight back.

struct Buffer {
    name: &'static str,
    bytes: Vec<u8>,
}

impl Drop for Buffer {
    fn drop(&mut self) {
        println!("free {} ({} bytes)", self.name, self.bytes.len());
    }
}

fn keep(buffer: Buffer) -> Buffer {
    buffer // ownership moves in and straight back out: nothing is freed here
}

fn main() {
    let input = Buffer { name: "input", bytes: vec![0; 1024] };
    let scratch = Buffer { name: "scratch", bytes: vec![0; 64] };
    {
        let _temp = Buffer { name: "temp", bytes: vec![0; 16] };
        println!("inner scope ends");
    } // `temp` is freed here, at the closing brace
    let input = keep(input);
    drop(scratch); // free early: `drop` takes ownership and lets it go
    println!("main ends with {} still owned", input.name);
} // `input` is freed here, exactly once

Sources: What is ownership? (the Book) · The Drop trait

Explore in Crabrix: Garbage collection vs deterministic drop · Drop & Scope

Deterministic drop compared with free() and a garbage collector

In C, malloc and free are your responsibility. Forget a free and memory leaks; call it twice, or use the pointer afterwards, and the behaviour is undefined: a crash much later, or a security hole. Rust keeps C's machine model of stack frames, heap allocations and fixed-width integers, but the compiler decides where memory is released and refuses programs that would touch it afterwards.

In a garbage-collected language such as JavaScript, Java or Go, a collector frees objects some time after they become unreachable. That is convenient, but the timing is not yours: finalisers may run late or never, so files, sockets and locks still need an explicit close() or try/finally, and the collector's pauses and memory headroom follow its heuristics rather than your code.

Because Rust ties cleanup to scope, one mechanism handles every resource. A File closes its descriptor in Drop, a MutexGuard releases its lock and a Vec frees its buffer. There are no collection pauses, and the cost of freeing appears at the closing brace where it happens. The price is that you must decide who owns each value, which is what the borrow checker teaches you.

Infographic with five enamel cards labelled Compiled, No GC, Ownership, Safe by default and Cargo above an orange paper crab mascot
Original generated infographic: Rust in five words, compiled ahead of time, no garbage collector, ownership, safe by default and Cargo.

Sources: std::sync::Mutex and MutexGuard

Explore in Crabrix: From malloc/free to Ownership · Ownership

What safe Rust rules out: use after free, null and data races

Most Rust code is safe Rust, in which the compiler upholds the memory rules for you, and safe Rust has no undefined behaviour. The classic C bugs cannot be written: use after free and double free are ruled out by ownership, dangling references by borrow checking, and reading a variable before it is initialised is error E0381.

Null dereference disappears because references are never null. When a value may be absent, its type says so: Option<T> is either Some(value) or None, and you cannot use the value until you have handled both cases. Out-of-bounds access is the one memory rule checked at run time. xs[i] with a bad index panics, and xs.get(i) returns None, so a bad index never reads neighbouring memory.

Data races are compile errors too. The Send and Sync traits, together with borrowing, decide which values may cross threads and how. In the example, two scoped threads add to one total, and the compiler accepts that only because total is reached through a Mutex. Our run printed user 1: ana, user 7: not found, readings.get(10) = None and total = 18.

use std::sync::Mutex;
use std::thread;

fn find_user(id: u32) -> Option<&'static str> {
    match id {
        1 => Some("ana"),
        _ => None, // no null: absence is a value the caller must handle
    }
}

fn main() {
    // No null dereference: the caller must decide what `None` means.
    for id in [1, 7] {
        match find_user(id) {
            Some(name) => println!("user {id}: {name}"),
            None => println!("user {id}: not found"),
        }
    }

    // No out-of-bounds read: `get` returns None instead of touching other memory.
    let readings = [3, 4, 5, 6];
    println!("readings.get(10) = {:?}", readings.get(10));

    // No data race: the threads can reach `total` only through its Mutex.
    let total = Mutex::new(0);
    thread::scope(|s| {
        for chunk in readings.chunks(2) {
            let total = &total;
            s.spawn(move || {
                let sum: i32 = chunk.iter().sum();
                *total.lock().unwrap() += sum;
            });
        }
    });
    println!("total = {}", total.into_inner().unwrap());
}

Sources: Behavior considered undefined (Rust Reference) · std::option · Fearless concurrency (the Book)

Explore in Crabrix: What Safe Rust Rules Out · Option & Result

What safe Rust does not rule out: leaks, deadlocks, panics, logic errors

Safe means free of undefined behaviour, not correct. The Rust Reference lists behaviour the compiler does not consider unsafe even though you would call it a bug: deadlocks, leaks of memory and other resources, exiting without running destructors, integer overflow and logic errors. A safe program can also panic, or run out of memory or stack.

Each of these is defined, which matters when you debug. A leak through Box::leak, std::mem::forget or an Rc cycle wastes memory but cannot corrupt it. A panic unwinds the thread and runs destructors, or aborts if configured to. Integer overflow panics in debug builds and wraps in release builds, so where it matters, choose checked_add, wrapping_add or saturating_add.

Our run printed v1-leaked, then None 4 255 for the three additions on a u8 holding 250, then second lock available: false while the guard was alive and true after drop(guard). Calling lock() instead of try_lock() at that point would have waited for ever, and the compiler would not have objected. Tests, review and careful design remain your job.

use std::sync::Mutex;

fn main() {
    // A leak is safe: the memory is never freed, but nothing can misuse it.
    let label: &'static mut String = Box::leak(Box::new(String::from("v1")));
    label.push_str("-leaked");
    println!("{label}");

    // Overflow is defined behaviour: say which result you want.
    let level: u8 = 250;
    println!("{:?} {} {}", level.checked_add(10), level.wrapping_add(10), level.saturating_add(10));

    // A deadlock is safe too: a second `lock()` here would wait for ever.
    let counter = Mutex::new(0);
    let guard = counter.lock().unwrap();
    println!("second lock available: {}", counter.try_lock().is_ok());
    drop(guard);
    println!("after drop: {}", counter.try_lock().is_ok());
}

Sources: Behavior not considered unsafe (Rust Reference) · std::mem::forget is safe

unsafe is an explicit, searchable boundary

When safe Rust cannot express something, such as calling C, driving hardware or building a low-level data structure, you write unsafe. It re-enables a short list of powers: dereferencing raw pointers, calling unsafe functions including every C function, accessing mutable statics, implementing unsafe traits and reading union fields. Type checking and the borrow checker stay on.

Inside an unsafe block undefined behaviour is possible again, and the whole program's safety rests on that block being right. So keep such blocks small, put a // SAFETY: comment above each one naming the invariant it relies on, and wrap it in a safe function that checks the invariant first. The standard library's Vec and Mutex are built exactly this way.

In the example, first_and_last skips bounds checks with get_unchecked only after proving the slice is not empty, and c_abs rejects INT_MIN, for which C's abs is undefined, before crossing the boundary. Edition 2024 requires unsafe extern for the C declarations. It printed Some((3, 5)) None and 42, natively and as WebAssembly. Because unsafe is a keyword, a reviewer can find every such place with one search.

unsafe extern "C" {
    fn abs(input: i32) -> i32; // from the C standard library
}

/// A safe function: it checks what the unsafe block relies on first.
fn first_and_last(values: &[u32]) -> Option<(u32, u32)> {
    if values.is_empty() {
        return None;
    }
    let last = values.len() - 1;
    // SAFETY: `values` is not empty, so indexes 0 and `last` are in bounds.
    let pair = unsafe { (*values.get_unchecked(0), *values.get_unchecked(last)) };
    Some(pair)
}

fn c_abs(x: i32) -> i32 {
    assert!(x != i32::MIN, "abs(INT_MIN) is undefined behaviour in C");
    // SAFETY: `abs` takes no pointers, and the one undefined input is excluded.
    unsafe { abs(x) }
}

fn main() {
    println!("{:?} {:?}", first_and_last(&[3, 4, 5]), first_and_last(&[]));
    println!("{}", c_abs(-42));
}

Sources: Unsafe Rust (the Book) · The unsafe keyword

Explore in Crabrix: unsafe, Raw Pointers and FFI

Zero-cost abstractions, made concrete with iterators

Zero-cost abstraction is a phrase Rust borrows from C++. The Rust Book quotes Bjarne Stroustrup: what you don't use, you don't pay for, and what you do use, you couldn't hand code any better. It does not mean free to compile. It means no run-time overhead compared with the code you would otherwise write by hand.

Iterators are the everyday example. filter, map and sum look like JavaScript's array methods, but they are lazy: nothing runs until sum pulls values through, and no intermediate array is built. Each closure has its own type, so the compiler specialises the pipeline and can inline it into a single loop.

We checked rather than assumed. Both functions below return 220 for the numbers 1 to 10. Compiled as a library with -C opt-level=3 for aarch64, each became 58 instructions of the same shape: no bounds check, no allocation, no call, and a main loop handling four values per pass without branches. Only register choice and the order of two instruction pairs differed, on this compiler and target, so still measure your own hot code.

/// The loop you might write by hand.
fn even_squares_loop(values: &[u64]) -> u64 {
    let mut total = 0;
    for i in 0..values.len() {
        let v = values[i];
        if v % 2 == 0 {
            total += v * v;
        }
    }
    total
}

/// The same work as an iterator chain: no intermediate Vec is built.
fn even_squares_iter(values: &[u64]) -> u64 {
    values.iter().filter(|&&v| v % 2 == 0).map(|&v| v * v).sum()
}

fn main() {
    let values: Vec<u64> = (1..=10).collect();
    println!("loop: {}", even_squares_loop(&values));
    println!("iter: {}", even_squares_iter(&values));
}

Sources: Performance in loops vs. iterators (the Book) · std::iter

Explore in Crabrix: Array methods vs iterators · Iterators

Cargo and crates.io: one tool for the whole project

Rust ships with Cargo, its build tool and package manager. Where C combines make, headers and a system package manager, and Node.js has npm and package.json, Rust has Cargo.toml and one command: cargo build, cargo run, cargo test for unit, integration and documentation tests, and cargo doc for API documentation from your comments.

Libraries are called crates and come from crates.io, the community registry. cargo add writes a dependency into Cargo.toml, and Cargo.lock records the exact versions that were resolved, so a later build uses the same ones. When we ran the commands below with Cargo 1.99, cargo new wrote edition = "2024" into the manifest, cargo add itoa added itoa = "1.0.19", and cargo run printed Hello, world!.

Most Rust projects build the same way: clone, run cargo build, and Cargo downloads, verifies and compiles the dependency graph. cargo fmt and cargo clippy are standard too.

cargo new hello-crab      # Cargo.toml, src/main.rs and a git repository
cd hello-crab
cargo run                 # builds target/debug/hello-crab, prints Hello, world!
cargo add itoa            # writes itoa = "1.0.19" under [dependencies]
cargo test                # unit, integration and documentation tests
cargo build --release     # optimised build in target/release/

Sources: The Cargo Book · First steps with Cargo · crates.io

Explore in Crabrix: npm and package.json vs Cargo · Headers and make to Cargo

Reading rustc errors: the compiler as a teacher

Many people meet Rust's compiler as an obstacle and later treat it as a teacher. Its diagnostics have a fixed anatomy worth learning on your first day. Below is real output for a program whose total takes a Vec<i32> by value, after which main uses the vector again: the same mistake as freeing a buffer in C and keeping the pointer.

Read it from the top. The first line gives the severity, the code and the rule: error[E0382]: borrow of moved value. The --> line gives the file, line and column. Under the source, ^^^ marks the primary span, where the rule is broken, and --- marks secondary spans that explain why: where the value was created, that Vec<i32> does not implement Copy, and where it moved. The note: points at the parameter that takes ownership, and help: proposes a change.

No program was built. In C the equivalent use after free compiles without a warning under -Wall -Wextra and fails, if you are lucky, under AddressSanitizer at run time. rustc --explain E0382 prints the rule with examples, offline.

$ rustc --edition 2024 readings.rs
error[E0382]: borrow of moved value: `readings`
 --> readings.rs:8:40
  |
6 |     let readings = vec![3, 4, 5];
  |         -------- move occurs because `readings` has type `Vec<i32>`, which does not implement the `Copy` trait
7 |     let sum = total(readings);
  |                     -------- value moved here
8 |     println!("{sum} from {} readings", readings.len());
  |                                        ^^^^^^^^ value borrowed here after move
  |
note: consider changing this parameter type in function `total` to borrow instead if owning the value isn't necessary
 --> readings.rs:1:18
  |
1 | fn total(values: Vec<i32>) -> i32 {
  |    -----         ^^^^^^^^ this parameter takes ownership of the value
  |    |
  |    in this function
help: consider cloning the value if the performance cost is acceptable
  |
7 |     let sum = total(readings.clone());
  |                             ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0382`.
A friendly terminal-shaped robot teacher with glasses hands an orange paper crab a page of code with amber underlines and a lightbulb note
Original generated illustration: rustc as a patient teacher, returning your code with the broken line underlined and a suggested fix.

Sources: Error code E0382

Explore in Crabrix: Reading rustc · Reading rustc Diagnostics (for C developers) · TypeScript types vs Rust types

Fix the first error, and treat help as evidence

The help: line suggests readings.clone(). That would compile, but it copies the whole vector to satisfy a function that only reads it. The note: points to the better fix: total does not need ownership, so it should borrow a slice, &[i32], and the caller passes &readings. Treat a suggestion as evidence about your program, not as an order, and decide first what the program should mean.

The corrected program printed 12 from 3 readings. Two habits help. Fix the first error and rebuild before reading the rest, because one root mistake can produce several later messages. And predict the result before you press Run: a prediction the compiler contradicts is when you learn something.

Errors and warnings are separate in Rust. An error means no program is built, and no flag lets it through. A warning, such as an unused variable, still produces a program; #![deny(warnings)] or RUSTFLAGS="-D warnings" in continuous integration turns warnings into errors, and cargo clippy adds hundreds of further lints.

// The fix the note points to: borrow the readings instead of taking them.
fn total(values: &[i32]) -> i32 {
    values.iter().sum()
}

fn main() {
    let readings = vec![3, 4, 5];
    let sum = total(&readings);
    println!("{sum} from {} readings", readings.len());
}

Sources: Clippy documentation

Explore in Crabrix: Borrowing

Editions let Rust change without breaking your code

Rust is designed so that code which compiles on one stable release keeps compiling on later ones, with rare exceptions for soundness fixes. Changes that would break old code, such as new keywords or stricter rules, wait for an edition: 2015, 2018, 2021 and 2024 so far. The 2024 edition became stable with Rust 1.85 in February 2025.

An edition is chosen per crate, in Cargo.toml or with rustc --edition. Crates on different editions link into one program, so a 2018 library and a 2024 application work side by side and the ecosystem never migrates at once. cargo fix --edition applies the mechanical changes, such as 2024's unsafe extern.

For a learner: start new projects on the latest edition, as cargo new does, and read older material with that in mind; nearly all of it still applies.

Sources: The Rust Edition Guide · Announcing Rust 1.85.0 and Rust 2024 · How Rust is made and release channels

Where Rust is used: Linux, Android and Windows

Rust is used where C and C++ were the default and memory safety matters. The Linux kernel added initial Rust support in version 6.1, released in December 2022. Its documentation now has a Rust section with a quick start, coding guidelines and a description of how Rust abstractions wrap the kernel's C interfaces for users such as drivers and file systems written in Rust.

Android's platform documentation states that Android supports developing native operating-system components in Rust, and describes the language as giving memory safety with performance comparable to C and C++, without a garbage collector. Google's security team has also written about memory-safe languages, Rust included, in Android 13.

Microsoft documents Rust development on Windows on Microsoft Learn and is a founding member of the Rust Foundation. Beyond operating systems, rustc's platform support page lists targets from Linux, macOS and Windows to microcontrollers and WebAssembly.

Sources: Rust in the Linux kernel documentation · Linux kernel Rust: general information · Linux 6.1 release summary (Kernel Newbies) · Android Rust introduction · Memory safe languages in Android 13 · Overview of developing on Windows with Rust

Why learn Rust, and how long does it take?

Why learn Rust? Three reasons hold up. You get native performance and memory use you can predict from the code. You get a compiler that rejects whole classes of bugs before the program exists, including the memory and threading bugs behind many C and C++ security fixes. And the ideas transfer: once you have reasoned about ownership, borrowing and absence, you notice them everywhere.

How long it takes depends on where you start. The Crabrix path Rust from Zero has 52 lessons, from What Rust Is to Send & Sync, and their own time estimates add up to about 12 hours. That covers what a beginner needs, not fluency: most learning happens afterwards, writing small programs, and ownership and lifetimes usually take longest to feel natural.

If you already program in C or Node.js, start with a bridge course. Rust for C Developers and Rust for Node.js Developers have 20 lessons each, under four hours of estimated time, and set your habits beside Rust: malloc and free beside ownership, NULL and errno beside Option and Result, npm beside Cargo, the garbage collector beside deterministic drop.

Explore in Crabrix: Rust for C Developers · Rust for Node.js Developers

A first-week Rust learning plan with Rust from Zero

A week of short daily sessions covers the first 17 steps of the Rust from Zero path: the first two units of Rust Basics and the start of the third. Their stated times add up to just under three hours, leaving room to repeat and vary each exercise.

Day 1: What Rust Is, Hello, Rust and Variables; build the example, then break it on purpose and read the error. Day 2: Printing Values, Numbers and Booleans. Day 3: Characters & Text and Reading rustc; create three controlled errors and write down the first line of each. Day 4: Compound Types, Operators & Casting and Block Expressions. Day 5: Functions, Parameters and Control Flow. Day 6: Ranges, Loops and Parsing Values.

Day 7 has no new lesson. Write a small program that parses a few numbers from text and prints their total and largest value, using only this week's material, and note every error you hit. What Rust Is and the bridge courses are on the website now and reach the iPhone and iPad app in Crabrix 1.2; the other lessons here are already in the app, where progress stays on your device.

Explore in Crabrix: Hello, Rust · Variables · Parsing Values · Open What Rust Is in the Playground

Three ways to learn Rust: on your own, AI-assisted or agent-first

Crabrix offers one Academy three ways. On your own: lessons, quick checks and compiler labs on the website and in the app, with no account. AI-assisted: read a lesson and ask your assistant about it; every lesson page has a Learn this lesson with AI prompt carrying its title, goal and link. Agent-first: connect Claude, Claude Code, Codex, Cursor or another MCP client to Crabrix Academy, and the agent finds lessons, explains them and sets the exercises.

The Academy server is public and read-only, with no sign-in: https://crabrix.com/mcp/academy, or locally npx -y crabrix@0.6.0 academy. It serves lessons, exercises, examples and learning paths, including Rust from Zero, and never sees your progress, projects or Playground rooms. Agents follow a published teaching contract: teach from the real lessons and link them, give hints before solutions, and leave the code to you.

An agent's review is labelled AI reviewed; only the checks in the Crabrix app record a lesson as passed, and the agent cannot change your progress. Crabrix 1.2, the next app version, adds Learn with your AI agent under Learn and a Learn this lesson with AI button on lessons. Whichever way you choose, start the same way: open What Rust Is, build the example and read what the compiler says.

# Claude Code: the read-only Academy as a remote MCP server
claude mcp add --transport http crabrix-academy https://crabrix.com/mcp/academy

# Codex
codex mcp add crabrix-academy --url https://crabrix.com/mcp/academy

# Clients that start local servers (Node.js 22 or newer)
npx -y crabrix@0.6.0 academy

Sources: Model Context Protocol

Explore in Crabrix: Learn Rust with your AI agent · All Crabrix courses · Playground

Explore the free Crabrix lessons →