Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rust for C++ Programmers

You have written C and C++ for years. You know what lives on the stack and what lives on the heap, you have chased a dangling pointer through a debugger at 2 AM, you have called OpenGL or Vulkan through a C API, and you know how a large project is compiled, linked and held together with CMake. You do not need another tutorial that explains what a pointer is.

This book teaches Rust starting from what you already know. Every chapter begins with the C++ you would write, shows the Rust equivalent, and spends its time on the places where your C++ intuition helps and, more importantly, where it misleads you.

What makes this book different

  • C++ first. RAII vs Drop, std::move vs Rust moves, std::mutex vs Mutex<T>, CMake vs Cargo, templates vs generics, shared_ptr vs Arc.
  • Interactive memory diagrams. Ownership, borrowing and lifetimes are explained with step-through diagrams of the stack and the heap, so you can watch exactly what a move or a borrow does.
  • Code you can run in the page. Every Rust example has a ▶ button that compiles and runs it on the official Rust Playground, and a link that opens it there so you can inspect the assembly.
  • Graphics and engine programming. After the general chapters, Part III applies everything to the problems you actually have: handles and arenas, ECS and the borrow checker, SIMD, OpenGL and Vulkan FFI, wgpu, and a small renderer.

Who this is for

You should be comfortable with:

  • C: the stack and the heap, pointers, manual memory management, file I/O, C APIs such as OpenGL and Vulkan, and basic computer architecture (caches, alignment, what a cache line is);
  • C++: classes, constructors and destructors, operator overloading, templates as a user, and the STL (containers, std::thread, std::mutex, streams);
  • building large projects: compilers, linkers, static and dynamic libraries, CMake.

You do not need modern C++ expertise. If you are not sure what an rvalue reference is or have never written a template metaprogram, that is fine: where Rust borrows an idea from modern C++, this book explains the idea from scratch.

How the book is organized

  • Getting started: how to read the book and how to set up the toolchain.
  • Part I: The language, from C++: Cargo, types, ownership, borrowing, lifetimes, enums, errors, traits, collections, closures, smart pointers and modules.
  • Part II: Systems programming: concurrency, memory layout and performance, unsafe, FFI with C and C++, macros, testing and tooling.
  • Part III: Graphics and engine programming: handles and arenas, ECS, math and SIMD, OpenGL, Vulkan, wgpu, OpenXR, the game loop, assets and build scripts, hot reloading, and a case study.

Status

The book is complete in English and Chinese. English is the source text, and the Chinese edition is translated from it; use the EN · 中 switch at the top of the page. Every runnable example is compiled and tested on each build. Corrections and suggestions are welcome; see Contributing.

License

The text and diagrams are licensed under CC BY 4.0: you may copy, translate, adapt and redistribute them, including commercially, as long as you credit this book and link to it. Code (examples and the site's scripts) is under the MIT license. See Contributing and translating.

How to read this book

Read Part I in order. Ownership, borrowing and lifetimes build on each other, and most of Rust's surprises for a C++ programmer are in those three chapters. After that, Part II and Part III can be read in any order; each chapter links back to what it relies on.

Conventions

Side-by-side code shows the C++ you would write next to the Rust equivalent:

C++

int square(int x) { return x * x; }

Rust

fn square(x: i32) -> i32 { x * x }
fn main() { assert_eq!(square(3), 9); }

Rust examples are live. Press ▶ to compile and run them on the Rust Playground; edit them first if you like. The link under each example opens it on the Playground, where the ⋯ menu next to Run shows the generated assembly, LLVM IR or MIR. Some examples hide setup lines; click the eye icon to show them.

Interactive diagrams have Back and Next buttons, a slider, and respond to the ← and → keys when focused. Where a diagram has tabs, the C++ tab and the Rust tab show the same program in both languages.

Callouts mark three kinds of aside:

C++ habit to unlearn

Places where doing what you would do in C++ leads you astray.

Under the hood

What the compiler generates and what it costs.

Engine note

How the topic plays out in graphics and engine code.

Toolchain setup

A C++ toolchain is something you assemble: a compiler (or three), a build system, a package manager, a debugger, a formatter, a linter and a test framework, each from a different vendor. Rust ships almost all of that as one install. This chapter gets it onto your machine and maps each piece to what you already use.

Installing with rustup

Install Rust with rustup, the official toolchain manager. On Linux and macOS:

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

On Windows, download and run rustup-init.exe from the same site. Rust on Windows uses the MSVC linker and Windows SDK by default, so install the "Desktop development with C++" workload of Visual Studio (or the Build Tools) first. You almost certainly have it already.

rustup installs into your home directory (~/.cargo and ~/.rustup) and puts these on your PATH:

ToolWhat it isC++ equivalent
rustcThe compilerclang++, g++, cl.exe
cargoBuild system, package manager, test runnerCMake + vcpkg/Conan + CTest
rustupInstalls and switches toolchains and targetsInstalling several compilers side by side
rustfmt / cargo fmtFormatterclang-format
clippy / cargo clippyLinterclang-tidy
rustdoc / cargo docDocumentation generatorDoxygen
rust-analyzerLanguage server for editorsclangd

Toolchains and targets

Rust releases a new stable compiler every six weeks, and new releases are backward compatible: code that compiles today keeps compiling. There is no reason to stay on an old compiler the way C++ projects often must.

rustup update                 # move to the newest stable compiler
rustup toolchain install nightly
rustup default stable
rustc --version

A project can pin a toolchain by committing a rust-toolchain.toml file, the equivalent of pinning a compiler version in your CI images:

[toolchain]
channel = "1.91"
components = ["rustfmt", "clippy"]

Cross-compilation is built in. A target triple is the name of the platform you compile for. It is the same naming scheme Clang and GCC use (clang --target=aarch64-linux-android), inherited from LLVM and GNU autoconf. The general form is:

<architecture>-<vendor>-<operating system>-<environment/ABI>

Despite the name, it often has four parts, and a part that does not apply is either written as unknown/none or left out:

TripleArchitectureVendorOSEnvironment / ABI
x86_64-pc-windows-msvcx86_64pcwindowsmsvc (links with MSVC, MSVC C++ ABI)
x86_64-pc-windows-gnux86_64pcwindowsgnu (MinGW)
x86_64-unknown-linux-gnux86_64unknownlinuxgnu (glibc)
aarch64-apple-darwinaarch64 (ARM64)appledarwin (macOS)
aarch64-apple-iosaarch64appleios
aarch64-linux-androidaarch64(omitted)linuxandroid (Bionic libc, Android ABI)
wasm32-unknown-unknownwasm32unknownunknown (no OS: the browser)
thumbv7em-none-eabihfThumb-2 (Cortex-M4/M7)none (bare metal)eabihf (hardware float)

So aarch64-linux-android reads "64-bit ARM, Linux kernel, Android environment": the vendor field is simply dropped, as Android's own toolchain does. The last part matters more than it looks: windows-msvc and windows-gnu produce binaries that cannot link against each other's C++ libraries, exactly as with MSVC and MinGW builds in C++.

rustc -vV prints your host triple (the host: line), and rustc --print target-list lists every triple the compiler knows. To build for another one, install its standard library with rustup and pass --target:

rustup target add aarch64-linux-android wasm32-unknown-unknown x86_64-pc-windows-msvc
cargo build --target wasm32-unknown-unknown

The standard library for each target is downloaded prebuilt. You still need a linker for the target platform (the Android NDK, for example), just as in C++.

Editors

Install rust-analyzer. It provides completion, go-to-definition, inline type hints and the compiler's errors as you type.

  • VS Code: install the rust-analyzer extension. For debugging, add CodeLLDB (Linux/macOS) or use the C/C++ extension's debugger (Windows).
  • JetBrains: RustRover, or the Rust plugin for CLion.
  • Visual Studio: no first-class support; most Windows developers use VS Code or RustRover for Rust and keep Visual Studio for debugging mixed C++ and Rust.
  • Vim, Emacs, Helix, Zed: all speak the language server protocol.
Inline type hints

rust-analyzer shows the inferred type of every let binding in grey. Leave this on while you learn. Rust infers more than C++ auto does (types flow backward from later uses too), and the hints show you what the compiler decided.

Debuggers and profilers you already know

Rust compiles to native code with standard debug info (DWARF on Linux and macOS, PDB on Windows), so your existing tools work:

  • GDB and LLDB work directly. rust-gdb and rust-lldb are wrappers that add pretty-printers for Vec, String, Option and friends.
  • Visual Studio's debugger and WinDbg read the PDBs, with natvis visualizers for standard types.
  • RenderDoc, Nsight Graphics, PIX and Radeon GPU Profiler do not care what language issued the API calls.
  • perf, VTune, Superluminal, Tracy, Instruments all work. Tracy has a Rust client (the tracy-client crate).

Your first project

cargo new hello
cd hello
cargo run

cargo new creates:

hello/
├── Cargo.toml      # project manifest: name, version, dependencies
├── .gitignore
└── src/
    └── main.rs     # the binary's entry point

src/main.rs:

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

cargo run compiles in debug mode into target/debug/hello and runs it. The commands you will use every day:

CommandWhat it does
cargo buildDebug build into target/debug/
cargo build --releaseOptimized build into target/release/
cargo run / cargo run --releaseBuild and run
cargo checkType-check only, no code generation (much faster)
cargo testBuild and run all tests
cargo fmtFormat the whole project
cargo clippyLint
cargo doc --openBuild API docs for your crate and all dependencies
C++ habit to unlearn

Do not benchmark debug builds. Rust's debug builds are much slower than C++ -O0 builds in relative terms, because so much of Rust (iterators, Option, small methods) relies on inlining. For games, set opt-level = 1 for your own code in debug and opt-level = 3 for dependencies. The Cargo chapter shows how.

The Playground

For quick experiments you do not need a project at all. The Rust Playground compiles and runs code in the browser, can show assembly, LLVM IR and MIR, and has the 100 most popular crates available. Every runnable example in this book uses it.

Exercises

  1. Install Rust, create a project with cargo new, and run it in debug and release mode. Find both binaries under target/.
  2. Set a breakpoint on the println! line in your debugger of choice and step into it. What do you see?
  3. Run cargo build -v and read the rustc command line Cargo runs. Compare it with what CMake passes to your C++ compiler.

Cargo, crates and the build

In C++, the language standard says nothing about how code is built. Every project chooses a build system, a package manager, a directory layout and a way to find headers and libraries, and connecting two projects means reconciling their choices. Rust settled all of this from the start. One tool, Cargo, builds every Rust project, and every library is published the same way. This is the biggest day-to-day productivity difference you will notice.

This chapter covers:

  • crates, the unit of compilation, and why there are no headers,
  • Cargo.toml compared with CMakeLists.txt,
  • dependencies, versions and the lock file,
  • features, the replacement for #ifdef and CMake options,
  • build profiles and optimization settings,
  • what gets linked, and how,
  • workspaces for large codebases.

Crates: the unit of compilation

In C++ the compiler sees one translation unit at a time: a .cpp file with all its headers pasted in. The linker stitches the object files together afterwards, and headers exist so each translation unit can know the declarations of the others.

In Rust the compiler sees a whole crate at a time. A crate is a tree of modules (source files) compiled together into one library or executable. Since the compiler sees every file of the crate at once, there is nothing to declare in advance:

  • no header files and no forward declarations,
  • no include guards or #pragma once,
  • functions and types can be used before they are defined, in any order,
  • no One Definition Rule to violate, because each item is defined in exactly one place.

When crate game depends on crate math, the compiler reads math's compiled metadata (an .rlib file), which contains its public API, generic function bodies and inlinable code. That metadata plays the role of headers, but it is generated by the compiler, so it can never disagree with the implementation.

C++Rust
Translation unit (.cpp + headers)Crate (a tree of .rs modules)
Header fileNothing; the compiler reads dependency metadata
Static library .a/.libLibrary crate (.rlib)
Executable targetBinary crate
CMake projectCargo package
vcpkg / Conan packageCrate on crates.io

A package is a directory with a Cargo.toml. It contains at most one library crate (src/lib.rs) and any number of binary crates (src/main.rs, src/bin/*.rs), plus tests, examples and benchmarks.

Cargo.toml

CMakeLists.txt

cmake_minimum_required(VERSION 3.20)
project(viewer VERSION 0.1.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)

find_package(glfw3 3.3 REQUIRED)
find_package(glm REQUIRED)

option(VIEWER_HOT_RELOAD "Hot reload" OFF)

add_executable(viewer src/main.cpp
                      src/renderer.cpp)
target_link_libraries(viewer glfw glm::glm)
if(VIEWER_HOT_RELOAD)
  target_compile_definitions(viewer
    PRIVATE HOT_RELOAD=1)
endif()

Cargo.toml

[package]
name = "viewer"
version = "0.1.0"
edition = "2024"

[dependencies]
winit = "0.30"
glam = "0.30"

[features]
hot-reload = []

There is no list of source files: Cargo finds src/main.rs and the compiler follows mod declarations from there. The edition selects a language edition (2015, 2018, 2021, 2024), similar to -std=c++17, except that crates of different editions link together freely. An edition can change syntax and defaults, but never the ABI or the standard library.

Dependencies and versions

Dependencies come from crates.io by default, but can also come from Git or a local path:

[dependencies]
glam = "0.30"                                 # crates.io, semver-compatible with 0.30.x
serde = { version = "1", features = ["derive"] }
ash = { version = "0.38", default-features = false, features = ["loaded"] }
my-math = { path = "../my-math" }             # a local crate
imgui-backend = { git = "https://github.com/example/imgui-backend", rev = "4f2a1c9" }

[dev-dependencies]   # only for tests, examples and benchmarks
criterion = "0.5"

[build-dependencies] # only for build.rs
cc = "1"

Version requirements follow semantic versioning: "0.30" means "any 0.30.x", and "1.4" means "1.4.0 or newer, but below 2.0". The first build resolves exact versions and records them in Cargo.lock. Commit Cargo.lock for applications so every build uses identical dependencies; cargo update moves to newer compatible versions deliberately.

Cargo downloads, builds and links dependencies from source with your compiler and your flags. There are no prebuilt binaries to mismatch: no "this library was built with a different _ITERATOR_DEBUG_LEVEL", no runtime library conflicts, no missing .lib for your compiler version.

Under the hood: two versions of one library

If two of your dependencies need incompatible versions of a crate (say rand 0.8 and rand 0.9), Cargo builds and links both. Symbols are mangled with a hash of the crate's identity, so there is no clash. Types from the two versions are distinct types, so you cannot accidentally pass one to the other. In C++ the same situation is an ODR violation that the linker may or may not catch.

Features: conditional compilation

Features are named, additive switches declared by a crate, used where C++ uses preprocessor definitions and CMake options:

[features]
default = ["png"]
png = ["dep:png"]          # enabling "png" pulls in the optional dependency
hot-reload = []
vulkan = ["dep:ash"]

[dependencies]
png = { version = "0.17", optional = true }
ash = { version = "0.38", optional = true }

In code, #[cfg(...)] includes or removes an item, like #if but on whole syntax items rather than text:

#[cfg(feature = "hot-reload")]
fn watch_shaders() {
    println!("watching shader directory");
}

#[cfg(not(feature = "hot-reload"))]
fn watch_shaders() {}

#[cfg(target_os = "windows")]
const PLATFORM: &str = "windows";
#[cfg(not(target_os = "windows"))]
const PLATFORM: &str = "not windows";

fn main() {
    watch_shaders();
    if cfg!(debug_assertions) {      // a boolean, for ordinary `if`s
        println!("debug build on {PLATFORM}");
    }
}

cargo build --features hot-reload enables a feature, and --no-default-features turns off the defaults. Features are meant to be additive: enabling one must not break code that does not use it, because if two crates in your build enable different features of a shared dependency, Cargo compiles that dependency once with the union of both.

Build profiles

Cargo has a dev profile (cargo build) and a release profile (cargo build --release). You can tune them, and you can tune them per dependency, which is invaluable for games:

[profile.dev]
opt-level = 1            # light optimization for your own code: still debuggable

[profile.dev.package."*"]
opt-level = 3            # fully optimize all dependencies, even in dev builds

[profile.release]
lto = "thin"             # link-time optimization across crates
codegen-units = 1        # better optimization, slower build
debug = "line-tables-only"  # keep symbols for profilers and crash reports
panic = "abort"          # no unwinding tables; a panic kills the process

[profile.profiling]      # a custom profile: cargo build --profile profiling
inherits = "release"
debug = true
CMake / compiler flagCargo setting
-O0 / -O2 / -O3opt-level = 0 / 2 / 3
-Os / -Ozopt-level = "s" / "z"
-gdebug = true
-flto=thinlto = "thin"
-DNDEBUGdebug-assertions = false (the default in release)
-fno-exceptionspanic = "abort" (roughly)
-march=nativeRUSTFLAGS="-C target-cpu=native" or .cargo/config.toml

debug_assertions controls debug_assert! and integer overflow checks. assert! is always on, like an assert that survives NDEBUG.

What ends up in the binary

By default, Rust links all Rust code statically. A Rust executable contains your code, every dependency and the parts of the standard library you use. It links dynamically only to the platform's C runtime and system libraries (libc, kernel32.dll, and so on), plus whatever C libraries you link explicitly.

Library crates can be built in other shapes by setting crate-type:

[lib]
crate-type = ["rlib", "cdylib", "staticlib"]
crate-typeProducesUse it for
rlib (default)Rust library with metadataOther Rust crates
staticlib.a / .lib with a C ABILinking Rust into a C or C++ program
cdylib.so / .dll / .dylib with a C ABIPlugins, loading from C/C++, WebAssembly
dylibRust-ABI shared libraryRarely; see hot reloading

Generic functions are compiled into the crate that uses them, with the concrete types filled in, exactly as templates are instantiated in each translation unit that uses them. Non-generic functions are compiled once, in their own crate, unless marked #[inline].

build.rs: the custom command

A build.rs file at the package root is a Rust program that Cargo compiles and runs before compiling your crate. It plays the role of CMake custom commands: compiling C code, generating bindings, compiling shaders, emitting link flags.

// build.rs
fn main() {
    // Rebuild only when the shader changes.
    println!("cargo::rerun-if-changed=shaders/triangle.wgsl");

    // Link a system library.
    println!("cargo::rustc-link-lib=dylib=vulkan");

    // Compile a C file into the crate with the `cc` build dependency.
    cc::Build::new().file("native/stb_image.c").compile("stb_image");
}

The FFI chapter and the assets chapter use build.rs in earnest.

Workspaces

A large project is a workspace: several packages that share one Cargo.lock, one target/ directory and common settings. It is the equivalent of a top-level CMakeLists.txt with add_subdirectory.

engine/
├── Cargo.toml          # [workspace]
├── crates/
│   ├── engine-math/
│   ├── engine-render/
│   ├── engine-ecs/
│   └── engine-assets/
└── apps/
    ├── editor/
    └── game/
# engine/Cargo.toml
[workspace]
members = ["crates/*", "apps/*"]
resolver = "3"

[workspace.package]
edition = "2024"
version = "0.1.0"

[workspace.dependencies]   # pick versions once, use them everywhere
glam = "0.30"
ash = "0.38"
# engine/crates/engine-render/Cargo.toml
[package]
name = "engine-render"
edition.workspace = true
version.workspace = true

[dependencies]
glam.workspace = true
ash.workspace = true
engine-math = { path = "../engine-math" }

Splitting a project into crates matters more than splitting C++ into libraries, because the crate is the unit of parallel and incremental compilation. A single huge crate compiles serially at the front end; a graph of mid-sized crates builds in parallel. The modules chapter discusses how to draw those boundaries.

Engine note: build times

Rust compile times are comparable to template-heavy C++. The levers you have:

  • Split the engine into crates along stable boundaries (math, ECS, renderer, assets), so a change rebuilds only what depends on it.
  • Use cargo check while editing; it skips code generation.
  • Optimize dependencies in dev builds (shown above) so you can run debug builds at playable frame rates.
  • On Linux, use a faster linker (mold or lld); linking is often the slowest step of an incremental build.
  • Share build caches across machines with sccache, the Rust analogue of ccache.

Summary

C++Rust
CMake, Meson, Bazel, MSBuild…Cargo
vcpkg, Conan, git submodulescrates.io and Cargo
Headers + translation unitsCrates; no headers
#ifdef / CMake optionsFeatures and #[cfg]
Build types (Debug/Release/RelWithDebInfo)Profiles, tunable per dependency
Custom commandsbuild.rs
add_subdirectoryWorkspaces

Exercises

  1. Create a workspace with a library crate geom (a Vec2 struct with an add function) and a binary crate that uses it. Run it with cargo run -p <name>.
  2. Add a feature double to geom that makes add print a message. Build the binary with and without --features geom/double.
  3. Run cargo tree in a project with a few dependencies and find a crate that appears more than once. Why is it there twice?

Values, types and layout

Rust's basic types look like C's, and they compile to the same machine representation. The differences are in the rules around them: no implicit conversions, defined overflow behavior, immutability by default, and a compiler that is free to reorder struct fields unless you ask it not to. This chapter walks through the types you will use in every program and how they are laid out in memory.

Variables: immutable by default

fn main() {
    let width = 1920;          // immutable: like `const auto width = 1920;`
    let mut frame = 0u64;      // mutable
    frame += 1;

    let height: u32 = 1080;    // explicit type
    let aspect = width as f32 / height as f32;
    println!("frame {frame}: {width}x{height}, aspect {aspect:.3}");
}

let is the only way to declare a local variable, and the type is inferred unless you write it. Variables are immutable unless declared mut. That reverses C++'s default, where you add const to opt out of mutability. In practice most locals in Rust code are immutable, and mut flags the few that change.

Shadowing lets you reuse a name for a new variable, often to change its type while keeping the meaning:

fn main() {
    let input = "  42 ";
    let input = input.trim();              // &str, trimmed
    let input: i32 = input.parse().unwrap(); // now an integer
    println!("{}", input + 1);
}

Each let creates a new variable; the old one still exists until the end of scope but is hidden. This is legal and idiomatic, unlike C++ where it is a warning at best.

Scalar types

RustC/C++Notes
i8 i16 i32 i64 i128int8_t … int64_t, __int128Fixed size, two's complement
u8 u16 u32 u64 u128uint8_t … uint64_t
isize usizeptrdiff_t, size_tPointer-sized; usize indexes everything
f32 f64float, doubleIEEE 754
boolbool1 byte, always 0 or 1
charchar32_tA Unicode scalar value, 4 bytes. Not a byte
()voidThe "unit" type: an empty tuple, zero bytes

There is no int, long or unsigned whose size depends on the platform. Integer literals default to i32 and float literals to f64 when nothing else constrains them. Literals can carry a suffix (255u8, 1.0f32) and underscores (1_000_000, 0xFF_FF_FF).

No implicit conversions

C++ silently converts between arithmetic types: int to double, double to float, size_t to int (with a warning, if you are lucky), and it promotes small integers to int before arithmetic. Rust does none of this. Mixing types is a compile error, and every conversion is spelled out:

fn main() {
    let count: u32 = 10;
    let len: usize = 4;
    let total = count + len;  // error[E0308]: mismatched types
}

The tools for converting:

use std::convert::TryFrom;

fn main() {
    let index: usize = 300;

    // `as`: always succeeds, truncates or wraps like a C cast. Use with care.
    let byte = index as u8;           // 300 -> 44
    let f = index as f32;              // 300.0
    let back = -1.7f32 as i32;         // -1: truncates toward zero
    let sat = 1e10f32 as i32;          // i32::MAX: float->int casts saturate

    // `From`/`Into`: only lossless conversions are provided.
    let wide: u64 = u64::from(42u32);
    let also_wide: f64 = 3.5f32.into();

    // `TryFrom`: checked conversion that can fail.
    let checked = u8::try_from(index);  // Err(..): 300 does not fit
    let ok = u8::try_from(200usize);    // Ok(200)

    println!("{byte} {f} {back} {sat} {wide} {also_wide} {checked:?} {ok:?}");
}

Use From/Into for widening, TryFrom when a value might not fit, and as when you really want C-cast semantics (often in hot numeric code, after checking ranges yourself).

C++ habit to unlearn

In C++, float x = 1 / 2; is 0 because the division is done in int. In Rust, let x: f32 = 1 / 2; does not compile: 1 / 2 is an integer expression and you cannot store it in an f32. You must write 1.0 / 2.0. The error is annoying for a week and then saves you a bug a month.

Integer overflow

In C++, signed overflow is undefined behavior and unsigned overflow wraps. In Rust, overflow is never undefined:

  • In debug builds, arithmetic overflow panics (stops the program with a message).
  • In release builds, it wraps (two's complement), unless you enable overflow-checks = true in the profile.

When wrapping or saturating is what you mean, say so explicitly. The methods make intent visible and behave the same in every build:

fn main() {
    let hp: u8 = 250;
    println!("{}", hp.wrapping_add(10));     // 4
    println!("{}", hp.saturating_add(10));   // 255
    println!("{:?}", hp.checked_add(10));    // None
    println!("{:?}", hp.overflowing_add(10)); // (4, true)

    // Hash functions and RNGs usually want wrapping arithmetic everywhere:
    use std::num::Wrapping;
    let mut h = Wrapping(2166136261u32);
    for b in b"hello" {
        h ^= *b as u32;
        h *= 16777619;
    }
    println!("fnv1a = {:#x}", h.0);
}

Floats

f32 and f64 are IEEE 754, exactly as in C++. Two differences matter:

  • Floats implement PartialEq and PartialOrd, but not Eq and Ord, because NaN != NaN. So you cannot sort a Vec<f32> with .sort() or use f32 as a HashMap key without saying how to handle NaN. Use v.sort_by(|a, b| a.total_cmp(b)). The operators chapter explains these traits.
  • There is no -ffast-math. The compiler will not reassociate float operations, so it does not auto-vectorize float reductions such as sums. The SIMD chapter shows how to vectorize them yourself.

Tuples and arrays

fn min_max(xs: &[f32]) -> (f32, f32) {
    let mut lo = f32::INFINITY;
    let mut hi = f32::NEG_INFINITY;
    for &x in xs {
        lo = lo.min(x);
        hi = hi.max(x);
    }
    (lo, hi)                       // a tuple: like std::pair / std::tuple
}

fn main() {
    let (lo, hi) = min_max(&[3.0, -1.0, 7.5]);  // destructuring
    println!("{lo} {hi}");

    let identity: [[f32; 4]; 4] = [
        [1.0, 0.0, 0.0, 0.0],
        [0.0, 1.0, 0.0, 0.0],
        [0.0, 0.0, 1.0, 0.0],
        [0.0, 0.0, 0.0, 1.0],
    ];
    let zeros = [0u8; 256];        // 256 zero bytes: [value; count]
    println!("{} {}", identity[3][3], zeros.len());
}

An array [T; N] has a fixed length known at compile time and lives inline, like a C array or std::array<T, N>. Unlike a C array it never decays to a pointer, it can be passed and returned by value, and indexing is bounds-checked: identity[4] with a constant index is a compile error, and with a runtime index it panics instead of reading out of bounds. Arrays of Copy types are themselves Copy.

Structs

#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec3 {
    x: f32,
    y: f32,
    z: f32,
}

impl Vec3 {
    const ZERO: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 0.0 };

    // An associated function: no `self`. The usual "constructor".
    fn new(x: f32, y: f32, z: f32) -> Vec3 {
        Vec3 { x, y, z }   // field init shorthand
    }

    // Methods take `self` explicitly.
    fn dot(self, o: Vec3) -> f32 {
        self.x * o.x + self.y * o.y + self.z * o.z
    }

    fn length(self) -> f32 {
        self.dot(self).sqrt()
    }
}

// A tuple struct: fields are .0, .1, ... Great for type-safe wrappers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct EntityId(u32);

// A unit struct: no fields, zero size.
struct Player;

fn main() {
    let v = Vec3::new(3.0, 4.0, 0.0);
    let up = Vec3 { y: 1.0, ..Vec3::ZERO };   // struct update syntax
    println!("{v:?} length={} dot={}", v.length(), v.dot(up));
    let id = EntityId(7);
    println!("{id:?} {}", std::mem::size_of::<Player>());
}

Things that are different from C++ classes:

  • No constructors. A struct literal must set every field, so there is no such thing as an uninitialized member. By convention a function called new builds the value, and Default (#[derive(Default)]) provides a zero-ish default.
  • No inheritance, no virtual, no protected. Behavior is shared through traits (Traits and generics).
  • Methods live in impl blocks, separate from the data. A type can have several impl blocks, even in different files of the same crate.
  • #[derive(...)] generates common trait implementations: Debug (printing), Clone, Copy, PartialEq, Hash, Default, and more. It is the replacement for writing boilerplate operators by hand.

Newtypes like EntityId(u32) cost nothing at run time, and the compiler will refuse to pass an EntityId where a TextureId(u32) is expected. Use them generously for IDs, handles and units.

Memory layout

Rust gives you exactly the layout control you have in C, but the default is different:

  • Without an attribute (repr(Rust)), the compiler may reorder fields to minimize padding. Field order in the source does not determine order in memory, and the layout is not stable between compiler versions.
  • #[repr(C)] lays fields out in declaration order with C's padding rules, exactly like the equivalent C struct. Use it for anything that crosses a boundary: GPU buffers, files, network packets, FFI.
  • #[repr(align(N))] raises the alignment, like alignas(N).
  • #[repr(transparent)] guarantees a single-field wrapper has the same layout and ABI as its field, so a newtype can be passed to C as the inner type.
  • #[repr(packed)] removes padding (reading fields then needs care, since references to unaligned fields are not allowed).
use std::mem::{align_of, size_of};

struct Loose {     // default repr: the compiler may reorder
    a: u8,
    b: u32,
    c: u8,
}

#[repr(C)]
struct LooseC {    // C layout: a, pad 3, b, c, pad 3
    a: u8,
    b: u32,
    c: u8,
}

/// A vertex uploaded to the GPU: layout must match the shader.
#[repr(C)]
#[derive(Clone, Copy)]
struct Vertex {
    position: [f32; 3],
    normal: [f32; 3],
    uv: [f32; 2],
}

#[repr(C, align(64))]
struct PerThreadCounter {   // one cache line each, to avoid false sharing
    value: u64,
}

fn main() {
    println!("Loose   {} bytes", size_of::<Loose>());   // 8: reordered
    println!("LooseC  {} bytes", size_of::<LooseC>());  // 12
    println!("Vertex  {} bytes", size_of::<Vertex>());  // 32
    println!("Counter {} bytes, align {}", size_of::<PerThreadCounter>(), align_of::<PerThreadCounter>());
    println!("Option<&u8> {} bytes", size_of::<Option<&u8>>()); // 8: no extra tag
}
Engine note

Anything you memcpy into a GPU buffer must be #[repr(C)], and should contain no padding you have not accounted for. The bytemuck crate checks this at compile time: #[derive(Pod, Zeroable)] refuses to compile a struct with padding or pointers, and bytemuck::cast_slice(&vertices) then gives you the &[u8] to upload, with no unsafe in your code. The OpenGL chapter uses it.

Everything is an expression

Blocks, if and match produce values, so the ternary operator is just if:

fn main() {
    let health = 35;
    let color = if health > 50 { "green" } else { "red" };

    let lod = {
        let distance = 120.0f32;
        let bias = 0.5;
        (distance.log2() - bias) as u32   // no semicolon: this is the block's value
    };

    let label = match lod {
        0 => "full",
        1..=3 => "reduced",
        _ => "impostor",
    };
    println!("{color} {lod} {label}");
}

A semicolon turns an expression into a statement whose value is (). That is why a function's last line has no semicolon: it is the return value. return exists for early returns.

Constants and statics

const MAX_LIGHTS: usize = 16;                  // inlined at each use, like constexpr
static GREETING: &str = "hello";               // one address in the binary
static FRAME_TIME: f64 = 1.0 / 60.0;

const fn kib(n: usize) -> usize { n * 1024 }   // evaluable at compile time
const STAGING_SIZE: usize = kib(64);

fn main() {
    let lights = [0u8; MAX_LIGHTS];            // constants work as array lengths
    println!("{} {GREETING} {FRAME_TIME} {STAGING_SIZE}", lights.len());
}

const is the closest match to constexpr variables. const fn is a function the compiler can run at compile time, like a constexpr function. static has a fixed address. Mutable globals (static mut) exist but every access is unsafe; the game loop chapter shows what to use instead.

Summary

C++Rust
auto x = 1; / const auto x = 1;let mut x = 1; / let x = 1;
int, long, size_ti32, i64, usize
Implicit conversions and promotionsNone; use as, From, TryFrom
Signed overflow is UBPanics in debug, wraps in release; wrapping_*, checked_*
std::array<T, N>[T; N]
std::pair, std::tuple(A, B)
Class with constructorStruct + new function
Default C layoutCompiler-chosen layout; #[repr(C)] for C layout
alignas(64)#[repr(align(64))]
constexprconst, const fn
cond ? a : bif cond { a } else { b }

Exercises

  1. Write fn lerp(a: f32, b: f32, t: f32) -> f32 and call it with an integer t. Read the error, then fix the call.
  2. Define a #[repr(C)] struct with fields u8, u64, u8, u32 and predict its size before printing size_of. Reorder the fields to make it as small as possible. Then remove repr(C) and see what the compiler does on its own.
  3. Write a function that adds two u8 values and returns None on overflow, using checked_add. Then make one that clamps to 255 instead.

Ownership and moves

You already know the core idea of this chapter. In C++ you write a class whose constructor acquires a resource and whose destructor releases it, and you rely on scope to run that destructor at the right time. That is RAII, and it is the best idea C++ has.

Rust takes RAII and makes it the only way resources are managed, then adds one thing C++ never had: the compiler tracks, for every value, which variable currently owns it. That one addition removes use-after-move, double free and most of the rule of five.

This chapter covers:

  • the three ownership rules, and how they map onto RAII,
  • what a move actually does in each language (they are surprisingly different),
  • Copy and Clone, the replacements for copy constructors,
  • Drop, the replacement for destructors, and drop order,
  • wrapping a GPU resource so it cannot leak or be freed twice.

The rules

  1. Every value has exactly one owner, a variable or a field.
  2. When the owner goes out of scope, the value is dropped (its destructor runs).
  3. Ownership can be moved to another variable, and then the old one can no longer be used.

Rules 1 and 2 are RAII exactly as you know it. Rule 3 is where Rust and C++ part ways.

What a move does

Here is the same function in both languages. Step through each tab, and pay attention to what happens to a.

Two differences matter:

C++Rust
Who performs the moveThe move constructor, user code that can do anythingThe compiler: a bitwise copy of the value's bytes
State of the sourceA live object in a "valid but unspecified" stateStatically inaccessible; using it is a compile error
Destructor of the sourceStill runs, so the move constructor must neutralize itDoes not run
Can a move throw / fail?Yes, unless marked noexceptNo, it is a memcpy

Because a Rust move is always a shallow byte copy, every type is movable and no type can customize how it moves. You never write a move constructor, and std::vector's old dilemma (copy elements on reallocation unless the move constructor is noexcept) does not exist: Vec always moves elements with memcpy.

Under the hood

"Bitwise copy" describes the semantics, not necessarily the machine code. The optimizer removes most moves entirely, just as C++ elides copies. If a move does show up in a profile, it is a memcpy of size_of::<T>() bytes. A Vec<T> is 24 bytes on a 64-bit target no matter how many elements it holds, so moving one is cheap. A [f32; 4096] is 16 KiB, so move it into a Box first if you pass it around by value.

Try it yourself. This program does not compile. Run it to see the error, then fix it by removing the bad line, or by using let b = a.clone(); to make an explicit deep copy.

fn main() {
    let a = vec![1, 2, 3];
    let b = a;
    println!("a has {} elements", a.len());
    println!("b has {} elements", b.len());
}

Moves into and out of functions

Passing an argument by value moves it, exactly like passing a std::unique_ptr<T> by value. There is no std::move to write, because the move is the default, and there is no null left behind.

Returning a value moves it out to the caller, which is how a function hands ownership back:

fn make_buffer(len: usize) -> Vec<f32> {
    let mut v = Vec::with_capacity(len);
    v.resize(len, 0.0);
    v // moved out to the caller; nothing is freed here
}

fn add_one(mut v: Vec<f32>) -> Vec<f32> {
    for x in &mut v {
        *x += 1.0;
    }
    v // ownership comes back
}

fn main() {
    let buf = make_buffer(4);
    let buf = add_one(buf); // move in, move out
    println!("{buf:?}");
}

Taking and giving back ownership works, but it is clumsy when a function only needs to look at or modify a value. That is what borrowing is for, and it is the subject of the next chapter. In practice most functions take references, and you move only when ownership really changes hands: pushing into a container, sending to another thread, storing in a struct.

C++ habit to unlearn

In C++, void f(std::string s) followed by f(name) silently copies the string, and you add std::move to avoid it. In Rust, f(name) moves, and you write f(name.clone()) when you really want a copy. Expensive operations are always visible in the source.

Copy types

Moving an i32 and then using the original would be silly: there is nothing to "own". Types whose bytes can be duplicated safely implement the Copy trait, and assignment copies them instead of moving them. The source stays usable.

#[derive(Clone, Copy, Debug)]
struct Vec3 {
    x: f32,
    y: f32,
    z: f32,
}

fn length(v: Vec3) -> f32 {
    (v.x * v.x + v.y * v.y + v.z * v.z).sqrt()
}

fn main() {
    let up = Vec3 { x: 0.0, y: 1.0, z: 0.0 };
    let also_up = up;                  // a copy, not a move
    println!("{}", length(up));        // `up` is still usable
    println!("{also_up:?}");
}

Integers, floats, bool, char, shared references, and arrays and tuples of Copy types are all Copy. A type can only be Copy if all its fields are, and if it has no Drop implementation. String, Vec and Box are never Copy, because duplicating their bytes would create two owners of one heap allocation.

The rule of thumb for engine code: small plain-data types such as vectors, matrices, colors, handles and IDs should derive Copy. Anything that owns a resource should not.

Clone is the explicit deep copy, the equivalent of a copy constructor that you must call by name. #[derive(Clone)] generates a member-wise clone, like a defaulted copy constructor.

C++Rust
Trivially copyable type#[derive(Clone, Copy)]
Copy constructorimpl Clone (called explicitly with .clone())
= delete copy constructorDo nothing: types are not copyable unless you opt in
Move constructor / move assignmentNothing to write: every move is a memcpy
Destructorimpl Drop

Drop: destructors

Drop is the destructor. It runs when the owner goes out of scope, and it runs at most once per value, because the compiler tracks moves.

struct Noisy(&'static str);

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("drop {}", self.0);
    }
}

struct Pair {
    first: Noisy,
    second: Noisy,
}

fn main() {
    let _a = Noisy("a");
    let _b = Noisy("b");
    let _p = Pair { first: Noisy("p.first"), second: Noisy("p.second") };
    let c = Noisy("c");
    drop(c); // explicit early drop: `c` is moved into `drop` and dies there
    println!("end of main");
}

Run it and read the output carefully:

  • Local variables are dropped in reverse order of declaration, like C++.
  • Struct fields are dropped in declaration order, which is the opposite of C++ (members are destroyed in reverse). This rarely matters, but it does when one field must outlive another, for example a Vulkan device and the objects created from it. Put the dependent objects first, or wrap the order-sensitive part in an explicit Drop for the parent struct.
  • drop(x) is not special. It is an ordinary function that takes its argument by value and does nothing, so the value is dropped when it returns.
Under the hood: drop flags

What if a value is moved on only one branch?

fn maybe_consume(v: Vec<u8>, flag: bool) {
    if flag {
        drop(v);
    }
    // is `v` dropped here?
}
fn main() { maybe_consume(vec![1], true); }

The compiler adds a hidden boolean "drop flag" on the stack, sets it when v is moved, and checks it at the end of scope. This is the only runtime cost of ownership tracking, and it only appears when moves are conditional.

Wrapping a GPU resource

Here is where ownership pays off for graphics code. In C++, a class that owns an OpenGL buffer name needs the full rule of five to be correct:

class GlBuffer {
public:
    explicit GlBuffer(GLsizeiptr size) { glGenBuffers(1, &id_); /* ... */ }
    ~GlBuffer() { if (id_) glDeleteBuffers(1, &id_); }

    GlBuffer(const GlBuffer&) = delete;             // no copies: double delete
    GlBuffer& operator=(const GlBuffer&) = delete;

    GlBuffer(GlBuffer&& o) noexcept : id_(o.id_) { o.id_ = 0; }   // steal, null out
    GlBuffer& operator=(GlBuffer&& o) noexcept {
        if (this != &o) {
            if (id_) glDeleteBuffers(1, &id_);
            id_ = o.id_;
            o.id_ = 0;
        }
        return *this;
    }
private:
    GLuint id_ = 0;   // 0 doubles as the "moved-from" marker
};

Every line of that is there to manage the moved-from state. In Rust there is no moved-from state, so the type is:

mod gl {
    pub type GLuint = u32;
    pub unsafe fn GenBuffers(_n: i32, ids: *mut GLuint) { unsafe { *ids = 1; } }
    pub unsafe fn DeleteBuffers(_n: i32, ids: *const GLuint) {
        println!("glDeleteBuffers({})", unsafe { *ids });
    }
}
pub struct GlBuffer {
    id: gl::GLuint, // never 0 while the struct exists
}

impl GlBuffer {
    pub fn new() -> GlBuffer {
        let mut id = 0;
        unsafe { gl::GenBuffers(1, &mut id) };
        GlBuffer { id }
    }
}

impl Drop for GlBuffer {
    fn drop(&mut self) {
        unsafe { gl::DeleteBuffers(1, &self.id) };
    }
}

fn main() {
    let a = GlBuffer::new();
    let b = a;            // move: `a` is gone, `b` owns the buffer
    let buffers = vec![b]; // move into a container
    drop(buffers);         // glDeleteBuffers runs exactly once
}

It is not Copy and not Clone, so it cannot be duplicated. Moves need no code. Drop runs exactly once. The 0 sentinel is gone, so the destructor has no if. (The gl module is stubbed out in a hidden part of the example so it runs in the browser. Click the eye icon to see it. The OpenGL chapter uses the real bindings.)

Engine note

Ownership is a tree: each value has one owner. Engines are full of things that are not trees: a mesh used by many entities, a texture referenced by many materials, a parent and child that point at each other. Rust has three answers, and you will meet all of them:

  • Borrowing for short-lived access (next chapter).
  • Shared ownership with Rc/Arc, the equivalents of shared_ptr (Smart pointers).
  • Handles into an arena that owns everything, which is usually the best fit for engines (Handles and arenas).

Leaving a value behind: take and replace

Sometimes you really do want the C++ behavior: move a value out of a struct field and leave something valid in its place. You cannot move out of a field you only borrowed, because that would leave a hole. Instead you swap something in explicitly:

use std::mem;

struct Frame {
    commands: Vec<String>,
}

impl Frame {
    /// Hand the recorded commands to the renderer and start a fresh list.
    fn flush(&mut self) -> Vec<String> {
        mem::take(&mut self.commands) // leaves Vec::new() behind
    }
}

fn main() {
    let mut f = Frame { commands: vec!["draw".into(), "dispatch".into()] };
    let submitted = f.flush();
    println!("{submitted:?}, left: {:?}", f.commands);

    let mut current = String::from("old");
    let previous = mem::replace(&mut current, String::from("new"));
    println!("{previous} -> {current}");
}

mem::take (for types with a Default), mem::replace and mem::swap are the explicit versions of the moved-from state. For optional fields, Option::take() does the same and leaves None behind. The difference from C++ is that the leftover value is one you chose, written in the source.

Summary

C++Rust
RAII is a conventionRAII is the only model; the compiler enforces it
std::move(x) casts; the move constructor moveslet y = x; moves, always a byte copy
Moved-from object is alive and must be validMoved-from variable cannot be used at all
Copy is implicit unless deletedCopy only for Copy types; otherwise .clone()
Rule of fiveImplement Drop if needed, derive Clone if wanted
Members destroyed in reverse orderFields dropped in declaration order

Exercises

  1. Change Vec3 above to remove Copy (keep Clone). What error do you get, and what are two ways to fix main?
  2. In the Noisy example, add a third field to Pair and predict the output before running it.
  3. Add a GlBuffer::into_raw(self) -> GLuint method that gives up ownership without deleting the buffer. Hint: look up std::mem::forget, and think about why it takes self by value.

Borrowing and references

Moving ownership every time a function needs to look at a value would be unworkable. Most of the time you want what C++ gives you with const T& and T&: access without ownership. Rust calls this borrowing, and its references look like C++ references with one big addition: the compiler checks that a reference can never outlive what it points to, and that nobody modifies data while someone else is reading it.

This chapter covers:

  • the two kinds of reference and the one rule that governs them,
  • why that rule rules out iterator and reference invalidation,
  • how long a borrow lasts,
  • slices, the safe std::span,
  • what the rule buys the optimizer,
  • the borrow-checker fights you will have in engine code, and their fixes.

Two kinds of reference

C++

float average(const std::vector<float>& v);
void normalize(std::vector<float>& v);

std::vector<float> samples = load();
float a = average(samples);
normalize(samples);   // nothing at the call site says it mutates

Rust

fn average(v: &Vec<f32>) -> f32 {
    v.iter().sum::<f32>() / v.len() as f32
}
fn normalize(v: &mut Vec<f32>) {
    let a = average(v);
    for x in v.iter_mut() { *x -= a; }
}
fn main() {
    let mut samples = vec![1.0, 2.0, 6.0];
    let a = average(&samples);
    normalize(&mut samples); // mutation is visible here
    println!("{a} {samples:?}");
}
  • &T is a shared reference: read-only access, like const T&. You can have as many as you like at the same time.
  • &mut T is a mutable reference: read-write access, like T&. While it exists, it is the only way to reach the value.

Both are plain pointers at run time, never null, and always point to a valid, initialized value. Unlike C++ references they are first-class values: you can reassign a let binding holding a reference, store references in structs, and put them in containers.

You also borrow explicitly at the call site: average(&samples), normalize(&mut samples). Reading a call tells you whether it can modify its argument, which C++ hides behind the function signature.

The rule: shared XOR mutable

At any point in the program, a value can have either any number of &T or exactly one &mut T, never both. Step through it:

While a shared borrow is in use, the owner is also frozen against writes: scores itself cannot be modified until a and b are done. While a mutable borrow is in use, the owner cannot even be read except through it.

This is a reader-writer lock, enforced at compile time, with zero runtime cost.

The bug this rule removes

Every C++ engineer has hit this, usually with std::vector<Entity> and a cached Entity* or iterator. Compare the two tabs:

The C++ program is undefined behavior that usually appears to work. The Rust program does not compile, and the error points at all three lines involved: where the borrow starts, where the conflicting mutation is, and where the borrow is used later.

The same rule covers modifying a container while iterating over it, holding a string_view into a std::string that gets reassigned, and a std::span over a vector that grows. These are all the same mistake: a reader holds a pointer into memory that a writer is about to move or free.

How long does a borrow last?

A borrow is alive from where it is created to its last use, not to the end of the enclosing block. The compiler computes this ("non-lexical lifetimes"), and most of the time you never think about it. When you do get an error, picture the live range of each reference. Hover the bars below to see which lines each borrow covers, and switch between the rejected program and two fixes:

Borrowing in methods

Methods choose how they access self, which is how the standard library encodes "this method mutates" or "this method consumes":

struct Mesh {
    positions: Vec<[f32; 3]>,
}

impl Mesh {
    fn vertex_count(&self) -> usize {          // like a const member function
        self.positions.len()
    }
    fn translate(&mut self, d: [f32; 3]) {     // non-const member function
        for p in &mut self.positions {
            p[0] += d[0];
            p[1] += d[1];
            p[2] += d[2];
        }
    }
    fn into_positions(self) -> Vec<[f32; 3]> { // consumes the mesh
        self.positions
    }
}

fn main() {
    let mut m = Mesh { positions: vec![[0.0; 3]; 3] };
    m.translate([1.0, 0.0, 0.0]);   // auto-borrows: (&mut m).translate(...)
    println!("{}", m.vertex_count());
    let raw = m.into_positions();    // `m` is moved; it cannot be used after this
    println!("{raw:?}");
}

The . operator borrows and dereferences automatically, so you write m.translate(...) rather than (&mut m).translate(...). Method calls are one of the very few places where Rust inserts a borrow for you.

Slices: the safe span

A slice &[T] is a pointer plus a length, a borrowed view of contiguous elements. It is std::span<const T>, and &mut [T] is std::span<T>, except that the borrow checker guarantees the underlying storage outlives the view and does not reallocate under it. &str is the same for UTF-8 text, the safe std::string_view.

Write functions that take slices rather than &Vec<T>. They then accept vectors, arrays, and sub-ranges:

fn max_abs(xs: &[f32]) -> f32 {
    xs.iter().fold(0.0, |m, x| m.max(x.abs()))
}

fn main() {
    let v = vec![0.5, -3.0, 2.0, 7.5];
    let a = [1.0, -9.0];
    println!("{}", max_abs(&v));       // &Vec<f32> coerces to &[f32]
    println!("{}", max_abs(&a));       // so does &[f32; 2]
    println!("{}", max_abs(&v[1..3])); // a sub-range: bounds-checked once
}

Indexing a slice is bounds-checked. An out-of-range index panics instead of reading past the end. In hot loops, iterating (for x in xs) avoids the checks entirely, and the iterators chapter shows how to confirm that in the assembly.

What the rule buys the optimizer

Because a &mut T is guaranteed to be the only path to its target, the compiler can assume it does not alias anything else. In C++ terms, every &mut is __restrict, and the compiler checks it for you.

C++

void add_twice(int& a, const int& b) {
    a += b;
    a += b;   // must reload b: a and b
              // might be the same int
}

Rust

pub fn add_twice(a: &mut i32, b: &i32) {
    *a += *b;
    *a += *b; // b cannot alias a: the
              // compiler folds this to
              // *a += 2 * *b
}
fn main() { let (mut x, y) = (1, 2); add_twice(&mut x, &y); assert_eq!(x, 5); }

Open the Rust version in the Playground (link under the example), choose Show Assembly in release mode, and compare with the C++ version in Compiler Explorer. The Rust version loads b once. In SIMD-heavy code such as skinning, particle updates or audio mixing, this is the difference between vectorizing and not, without sprinkling __restrict around and hoping it is true.

Fights you will have, and the fixes

The borrow checker reasons about whole values, plus individual fields of a struct when it can see them directly. Most surprises in engine code come from that boundary.

Two mutable elements of one array

fn main() {
    let mut bodies = vec![[0.0f32; 3]; 4];
    let a = &mut bodies[0];
    let b = &mut bodies[1]; // error: `bodies` already borrowed mutably
    a[0] += b[0];
}

The checker does not know that indices 0 and 1 differ. The standard library does the reasoning for you with split_at_mut, which hands out two non-overlapping &mut slices:

fn main() {
    let mut bodies = vec![[0.0f32, 1.0, 0.0]; 4];
    let (left, right) = bodies.split_at_mut(1);
    let (a, b) = (&mut left[0], &mut right[0]); // bodies[0], bodies[1]
    a[1] += b[1];
    // Or, for any two distinct indices (Rust 1.86+):
    if let Ok([x, y]) = bodies.get_disjoint_mut([0, 3]) {
        x[0] = y[1];
    }
    println!("{bodies:?}");
}

Borrowing two fields through a method

Borrowing two different fields directly is fine. Borrowing them through methods is not, because a method signature &mut self claims the whole struct:

struct World {
    transforms: Vec<[f32; 3]>,
    velocities: Vec<[f32; 3]>,
}

impl World {
    fn integrate(&mut self, dt: f32) {
        // Fine: two disjoint fields, borrowed directly.
        for (p, v) in self.transforms.iter_mut().zip(&self.velocities) {
            for i in 0..3 {
                p[i] += v[i] * dt;
            }
        }
        // Would NOT compile: each call borrows all of `self`.
        // let t = self.transforms_mut();
        // let v = self.velocities();
    }
}

fn main() {
    let mut w = World { transforms: vec![[0.0; 3]], velocities: vec![[1.0, 2.0, 3.0]] };
    w.integrate(0.5);
    println!("{:?}", w.transforms);
}

The fixes, in order of preference: access the fields directly inside the impl; write one method that returns both borrows at once (fn parts_mut(&mut self) -> (&mut A, &B)); or split the struct so the parts that change together live together. The last one is the road to an ECS, which has its own chapter.

Long-lived pointers between objects

Storing &Enemy inside Missile to remember its target works for a few lines of code and then fails, because the borrow would freeze the whole enemy list for as long as the missile exists. References are for temporary access. For long-lived relationships between objects, use handles into an arena, or shared ownership with Rc/Arc.

C++ habit to unlearn

In C++ it is normal to keep a raw pointer to "the thing I'm working with" as a member. In Rust, a struct that holds a reference needs a lifetime parameter and borrows its target for its whole life. That is occasionally right (parsers, views, iterators), but for game objects it almost never is. If you find yourself adding <'a> to a struct to make the borrow checker happy, step back and ask who should own the data.

No null, no dangling

Two guarantees fall out of everything above:

  • References are never null. "Maybe a reference" is Option<&T>, which the compiler stores as a plain nullable pointer, so it costs nothing, and match/if let forces you to handle the None case.
  • References never dangle. Returning a reference to a local is rejected, and so is keeping one past the lifetime of its owner. The next chapter explains how the compiler proves this across function boundaries.

Summary

C++Rust
const T&&T, many at once
T&&mut T, exclusive
const T* / T* that may be nullOption<&T> / Option<&mut T>
std::span<const T>, std::string_view&[T], &str
__restrict (unchecked promise)every &mut T (checked)
Invalidation is UB at run timeInvalidation is a compile error
const member function&self method

Exercises

  1. In the invalidation example above, make the Rust version compile in three different ways. Which one corresponds to what you would do in C++?
  2. Write fn largest<'a>(a: &'a [f32], b: &'a [f32]) -> &'a [f32] that returns the slice with the larger sum. Then try removing the 'a annotations and read the error. (The lifetimes chapter explains it.)
  3. Implement fn swap_ends(xs: &mut [i32]) that swaps the first and last element, using split_at_mut rather than xs.swap. Handle empty slices.

Lifetimes

The previous chapter showed that the compiler tracks how long each borrow is used. This chapter is about the other half of the proof: making sure the owner lives at least that long. In C++ this is the dangling pointer problem: returning a pointer to a local, keeping a string_view to a temporary, storing a reference to an object that gets destroyed. Rust rules all of these out at compile time, and lifetimes are the notation for how it does so across function boundaries.

The most important fact first: lifetimes do not exist at run time. They do not change what code is generated, they do not extend how long anything lives, and they cost nothing. A lifetime annotation is a statement to the compiler about which references are related, so it can check your program.

This chapter covers:

  • what a lifetime is, and watching a borrow outlive its owner,
  • lifetime annotations on functions, and the elision rules that make most of them unnecessary,
  • structs that hold references,
  • 'static,
  • reading the common error messages.

A borrow must not outlive its owner

Step through this program. It is the Rust version of returning a pointer to a local variable.

The compiler gives every reference a lifetime: the region of code where it must remain valid. Here, r is used on the last line, so the borrow &s must be valid until then. But s is dropped at the inner closing brace. The lifetime of the borrow is longer than the life of the value it points to, so the program is rejected with error E0597, "s does not live long enough".

Lifetimes in function signatures

Inside one function the compiler can see everything and needs no help. Across function calls it only sees signatures. Consider:

fn longest(a: &str, b: &str) -> &str {   // error[E0106]: missing lifetime specifier
    if a.len() >= b.len() { a } else { b }
}
fn main() {}

The caller needs to know: the returned reference points into which argument? It decides how long the caller must keep each argument alive. You answer with a lifetime parameter:

fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    let name = String::from("Vulkan");
    let result;
    {
        let other = String::from("GL");
        result = longest(&name, &other);
        println!("{result}");   // fine: both strings are alive here
    }
    // println!("{result}");    // error: `other` does not live long enough
}

Read <'a> like a template parameter, but for regions of code instead of types. The signature says: "there is some region 'a during which both a and b are valid, and the result is valid for that same region." At the call site the compiler picks the largest region that satisfies both arguments, which is the scope of other, and then checks every use of result against it. Uncomment the last line to see the error.

Lifetimes are written 'a, 'b, 'src and so on. The names mean nothing beyond tying references together.

Elision: why you rarely write them

Most functions need no annotations, because the compiler applies three elision rules to fill them in:

  1. Each reference parameter gets its own lifetime.
  2. If there is exactly one input lifetime, it is used for all output references.
  3. If there is a &self or &mut self parameter, its lifetime is used for all output references.

So these signatures are complete as written:

struct Texture {
    name: String,
    pixels: Vec<u8>,
}

impl Texture {
    // Rule 3: the result borrows from `self`.
    fn name(&self) -> &str {
        &self.name
    }
    // Rule 3 again.
    fn row(&self, y: usize, width: usize) -> &[u8] {
        &self.pixels[y * width * 4..(y + 1) * width * 4]
    }
}

// Rule 2: one input reference, so the output borrows from it.
fn file_stem(path: &str) -> &str {
    path.rsplit('/').next().unwrap_or(path).split('.').next().unwrap_or(path)
}

fn main() {
    let t = Texture { name: "brick".into(), pixels: vec![0; 4 * 4 * 2] };
    println!("{} {} {}", t.name(), t.row(1, 2).len(), file_stem("assets/brick.png"));
}

You need explicit lifetimes only when the rules are ambiguous: several input references and a returned reference (like longest), or structs that hold references.

Under the hood

Lifetimes are checked by the borrow checker, which runs on MIR, a simplified control-flow graph of each function. It computes, for every reference, the set of program points where it is live, and checks that the borrowed value is not moved, dropped or mutated in a conflicting way at any of them. Then the lifetimes are erased. The machine code is identical to what you would get from the same program with raw pointers.

Structs that hold references

A struct can hold references if it declares the lifetime they borrow for. The annotation says "a value of this type cannot outlive the data it borrows":

/// A zero-copy tokenizer over a shader source string.
struct Tokens<'src> {
    rest: &'src str,
}

impl<'src> Tokens<'src> {
    fn new(source: &'src str) -> Self {
        Tokens { rest: source }
    }
}

impl<'src> Iterator for Tokens<'src> {
    type Item = &'src str;   // tokens borrow from the source, not from the tokenizer

    fn next(&mut self) -> Option<&'src str> {
        let s = self.rest.trim_start();
        if s.is_empty() {
            return None;
        }
        let end = s.find(|c: char| c.is_whitespace() || c == ';').unwrap_or(s.len()).max(1);
        let (tok, rest) = s.split_at(end);
        self.rest = rest;
        Some(tok)
    }
}

fn main() {
    let source = String::from("uniform mat4 mvp; in vec3 pos;");
    let tokens: Vec<&str> = Tokens::new(&source).collect();
    println!("{tokens:?}");
    // drop(source); // error: `tokens` still borrows from `source`
}

This is the safe version of the C++ "view" types: std::string_view, std::span, iterators. A Tokens cannot outlive source, and neither can the tokens it produced. Note the Item = &'src str: the tokens borrow from the original string, not from the tokenizer, so the tokenizer can be dropped while the tokens are still in use.

Use reference-holding structs for short-lived views, parsers and iterators. For long-lived objects like game entities, store owned data or handles (Handles and arenas). A lifetime parameter spreads to every type that contains it, which is a good signal that you are borrowing for too long.

'static

'static is the lifetime of the whole program. Two different things carry it:

  • References &'static T point to data that lives forever: string literals (stored in the binary), static items, and leaked allocations (Box::leak).
  • Type bounds T: 'static mean "T contains no non-static references": it owns all its data. String, Vec<u8> and i32 all satisfy T: 'static. It does not mean the value lives forever.

The second meaning is common in APIs. std::thread::spawn requires F: 'static because the new thread may outlive the caller, so the closure must not borrow the caller's locals:

use std::thread;

fn main() {
    let level_name = String::from("e1m1");
    let handle = thread::spawn(move || {
        // `move` transfers ownership of `level_name` into the thread,
        // making the closure 'static.
        format!("loaded {level_name}")
    });
    println!("{}", handle.join().unwrap());
}

Remove move and you get an error explaining that the closure may outlive the function that borrows level_name. The concurrency chapter shows scoped threads, which can borrow.

C++ habit to unlearn

When the compiler says a value "does not live long enough", the C++ reflex is to make it live longer: allocate it on the heap, make it static. Usually the better fix is to make the borrow shorter (use the reference earlier, copy the small value you need, or return owned data such as String instead of &str). Returning owned data costs an allocation, and in exchange removes a lifetime from every caller.

Decoding the common errors

ErrorMeaningUsual fix
E0106 missing lifetime specifierA signature is ambiguous about what a returned reference borrows fromAdd a lifetime parameter, or return owned data
E0499 cannot borrow as mutable more than onceTwo &mut to the same value are alive at onceEnd the first borrow earlier; split the borrow (split_at_mut, separate fields)
E0502 cannot borrow as mutable because it is also borrowed as immutableA & and a &mut overlapReorder, copy the value out, or restructure
E0505 cannot move out because it is borrowedMoving a value while a reference to it is aliveUse the reference first, or clone
E0597 does not live long enoughThe owner is dropped while a borrow is still usedMove the owner to a longer-lived scope, or shorten the borrow
E0716 temporary value dropped while borrowedBorrowing from a temporary that dies at the end of the statement, like let s = String::from("x").as_str();Bind the temporary to a variable first
E0373 closure may outlive the current functionA closure that must be 'static borrows a localAdd move

Run rustc --explain E0597 (or any code) for a full explanation with examples.

Summary

C++Rust
Dangling pointer / referenceCompile error (E0597, E0716)
"Don't keep this string_view past the string's life" (comment)struct View<'a> (checked)
Iterator invalidationCompile error (previous chapter)
No equivalentLifetime parameters: relate the regions where references are valid
static storage duration'static references; T: 'static means "owns its data"

Exercises

  1. Write fn first_word(s: &str) -> &str without annotations. Which elision rule applies? Then write fn pick<'a, 'b>(a: &'a str, b: &'b str) -> &'a str that always returns a, and explain why it is more flexible for callers than longest.
  2. Make the Tokens example's Item type &str with no lifetime (elided to the &mut self borrow) and read the error. Why can't next return a reference tied to &mut self here?
  3. Write a struct Config that owns a String, and a method fn get(&self, key: &str) -> Option<&str> that returns a slice of it. Which lifetime does the return value get?

Enums and pattern matching

If you take one feature from Rust back to C++, it will be this one. A Rust enum is a tagged union: a type that is exactly one of several variants, each of which can carry its own data. You have written this by hand in C (a struct with a kind field and a union), and C++17 gave you std::variant and std::visit. Rust makes it a core language feature, and pairs it with match, a switch that checks you handled every case.

This chapter covers:

  • C-style enums and enums with data,
  • match and exhaustiveness,
  • Option<T>, the replacement for null,
  • patterns everywhere: if let, let else, destructuring,
  • how enums are laid out in memory, including the niche optimization,
  • an example: a render command list.

C-style enums

The simplest enums are what you know from C++ enum class: named constants in their own namespace, with no implicit conversion to integers.

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BlendMode {
    Opaque,
    AlphaBlend,
    Additive,
}

#[derive(Debug, Clone, Copy)]
#[repr(u32)]             // pick the underlying integer, for FFI or serialization
enum PrimitiveTopology {
    Points = 0,
    Lines = 1,
    Triangles = 3,
}

fn main() {
    let mode = BlendMode::AlphaBlend;
    let topo = PrimitiveTopology::Triangles;
    println!("{mode:?} {}", topo as u32);   // enum -> integer with `as`
}

Converting the other way, from an integer to an enum, is not a cast in Rust because most integers are not valid variants. Write a TryFrom implementation or a match.

Enums with data

Each variant can carry its own fields, like a struct or a tuple:

#[derive(Debug)]
enum Light {
    Directional { direction: [f32; 3] },
    Point { position: [f32; 3], radius: f32 },
    Spot { position: [f32; 3], direction: [f32; 3], angle: f32 },
    Ambient(f32),
}

fn shadow_cost(light: &Light) -> u32 {
    match light {
        Light::Directional { .. } => 4,                 // cascades
        Light::Point { radius, .. } if *radius > 10.0 => 6,
        Light::Point { .. } => 6,
        Light::Spot { angle, .. } => if *angle > 1.0 { 2 } else { 1 },
        Light::Ambient(_) => 0,
    }
}

fn main() {
    let lights = vec![
        Light::Directional { direction: [0.0, -1.0, 0.0] },
        Light::Point { position: [0.0; 3], radius: 5.0 },
        Light::Spot { position: [0.0; 3], direction: [0.0, 0.0, 1.0], angle: 0.6 },
        Light::Ambient(0.1),
    ];
    let total: u32 = lights.iter().map(shadow_cost).sum();
    println!("shadow passes: {total}");
}

A Light value is one of the four variants. You cannot read radius from a Directional light, because the only way to get at the fields is to match on the variant first. Compare with the C version:

struct Light {
    enum Kind { Directional, Point, Spot, Ambient } kind;
    union {
        struct { float direction[3]; } directional;
        struct { float position[3]; float radius; } point;
        /* ... */
    };
};
// Nothing stops you reading light.point.radius when kind == Directional.

and with std::variant, which is safe but verbose: a separate struct per alternative, std::visit with an overload set of lambdas, and error messages that span pages.

match is exhaustive

A match must cover every possible value. Delete the Light::Ambient(_) arm above and run it: the compiler rejects the program and names the missing variant. This is the feature that makes enums so useful in a large codebase. When you add a variant, the compiler lists every match that needs updating. C++ compilers can warn about missing case labels in a switch over an enum, but only for plain enums, only as a warning, and never for std::variant.

match arms are tried top to bottom, and the first matching pattern wins. There is no fall-through and no break. Patterns can:

PatternMatches
Light::Point { radius, .. }A variant, binding a field, ignoring the rest
3 / 'a' / "text"A literal
1..=9An inclusive range
A | BEither pattern
x @ 1..=9A range, binding the value to x
_Anything, without binding
nameAnything, binding it to name
pat if conditionA pattern plus a guard expression
(a, b), [first, .., last], Vec3 { x, .. }Tuples, slices, structs

_ as the last arm accepts everything else. Use it sparingly with your own enums, because it also silences the exhaustiveness check for variants you add later.

Option<T>: no more null

Option is an ordinary enum from the standard library:

enum Option<T> {
    None,
    Some(T),
}
fn main() {}

It is how Rust says "a value or nothing". There is no null pointer in safe Rust, so a function that might not find something returns Option, and the caller cannot use the result without dealing with the None case:

struct Scene {
    names: Vec<String>,
}

impl Scene {
    fn find(&self, name: &str) -> Option<usize> {
        self.names.iter().position(|n| n == name)
    }
}

fn main() {
    let scene = Scene { names: vec!["camera".into(), "sun".into()] };

    match scene.find("sun") {
        Some(i) => println!("sun is object {i}"),
        None => println!("no sun"),
    }

    // Shorthand forms you will use constantly:
    if let Some(i) = scene.find("camera") {
        println!("camera is object {i}");
    }
    let player = scene.find("player").unwrap_or(0);        // default value
    let count = scene.find("sun").map(|i| i + 1);           // transform if present
    let must = scene.find("camera").expect("scene needs a camera"); // panic if None
    println!("{player} {count:?} {must}");
}

unwrap() and expect() panic on None. They are fine in prototypes, tests and cases that are truly impossible, and should otherwise be rare. The error-handling chapter covers Result, the sibling of Option for operations that fail with an error.

Patterns beyond match

#[derive(Debug, Clone, Copy)]
struct Vec2 {
    x: f32,
    y: f32,
}

fn parse_size(s: &str) -> Option<(u32, u32)> {
    // let-else: bind or bail out. The else branch must diverge (return, break, panic).
    let Some((w, h)) = s.split_once('x') else {
        return None;
    };
    Some((w.parse().ok()?, h.parse().ok()?))
}

fn main() {
    let Vec2 { x, y } = Vec2 { x: 1.0, y: 2.0 };   // destructure a struct
    let (w, h) = parse_size("1920x1080").unwrap();  // destructure a tuple
    println!("{x} {y} {w} {h}");

    let samples = [3, 9, 4, 1];
    if let [first, .., last] = samples {             // slice patterns
        println!("first {first}, last {last}");
    }

    let mut stack = vec![1, 2, 3];
    while let Some(top) = stack.pop() {              // loop until None
        print!("{top} ");
    }
    println!();

    for (i, name) in ["albedo", "normal"].iter().enumerate() { // tuple pattern in for
        println!("{i}: {name}");
    }
}

Memory layout

An enum is stored as a tag (discriminant) plus enough space for its largest variant, exactly like the hand-written C version. The compiler picks the tag size and may tuck it into padding.

The compiler also uses niches: bit patterns a type can never hold. A reference is never null, so Option<&T> uses the null pointer to represent None, and is the same size as a raw pointer. The same holds for Box<T>, NonZeroU32, bool (values 2 to 255 are free) and enums with spare discriminants.

use std::mem::size_of;
use std::num::NonZeroU32;

#[allow(dead_code)]
enum Shape {
    Circle { r: f32 },
    Rect { w: f32, h: f32 },
}

fn main() {
    println!("&u64              {}", size_of::<&u64>());              // 8
    println!("Option<&u64>      {}", size_of::<Option<&u64>>());      // 8: null is None
    println!("Option<Box<u64>>  {}", size_of::<Option<Box<u64>>>());  // 8
    println!("Option<u32>       {}", size_of::<Option<u32>>());       // 8: needs a tag
    println!("Option<NonZeroU32> {}", size_of::<Option<NonZeroU32>>()); // 4: 0 is None
    println!("Shape             {}", size_of::<Shape>());             // 12: tag + 2 floats
    println!("Option<Shape>     {}", size_of::<Option<Shape>>());     // 12: spare tag values
}

So "use Option instead of null" costs nothing for pointers. That is why Option<Box<Node>> is the standard way to write a nullable owning pointer.

Example: a render command list

Enums shine for command buffers, events, messages and state machines. Here is a small command list a game thread could build and a render thread could consume:

#[derive(Debug, Clone, Copy, PartialEq)]
enum Pipeline {
    Opaque,
    Transparent,
}

#[derive(Debug)]
enum Command {
    SetViewport { x: u32, y: u32, w: u32, h: u32 },
    BindPipeline(Pipeline),
    Draw { mesh: u32, instances: u32 },
    Clear([f32; 4]),
}

fn execute(cmds: &[Command]) -> (u32, u32) {
    let mut draw_calls = 0;
    let mut pipeline_changes = 0;
    let mut current = None;

    for cmd in cmds {
        match *cmd {
            Command::Clear(color) => println!("clear to {color:?}"),
            Command::SetViewport { x, y, w, h } => println!("viewport {w}x{h} at ({x}, {y})"),
            Command::BindPipeline(p) if current == Some(p) => {} // redundant bind: skip
            Command::BindPipeline(p) => {
                current = Some(p);
                pipeline_changes += 1;
            }
            Command::Draw { instances: 0, .. } => {}             // nothing to draw
            Command::Draw { mesh, instances } => {
                draw_calls += 1;
                println!("draw mesh {mesh} x{instances} with {:?}", current.unwrap());
            }
        }
    }
    (draw_calls, pipeline_changes)
}

fn main() {
    let cmds = vec![
        Command::Clear([0.1, 0.1, 0.1, 1.0]),
        Command::SetViewport { x: 0, y: 0, w: 1280, h: 720 },
        Command::BindPipeline(Pipeline::Opaque),
        Command::Draw { mesh: 1, instances: 100 },
        Command::BindPipeline(Pipeline::Opaque),
        Command::Draw { mesh: 2, instances: 0 },
        Command::BindPipeline(Pipeline::Transparent),
        Command::Draw { mesh: 3, instances: 4 },
    ];
    println!("{:?}", execute(&cmds));
    println!("each command is {} bytes", std::mem::size_of::<Command>());
}

Add a Dispatch { x: u32, y: u32, z: u32 } variant and the compiler points at execute until you handle it.

Engine note

Every Command is as large as its largest variant (here 20 bytes). For a command stream with a few rare, very large variants, box the large payload (Upload(Box<UploadInfo>)) so the common commands stay small and the vector stays dense, the same trade-off as with std::variant.

Summary

C / C++Rust
enum classenum without data
Hand-written tagged union / std::variantenum with data
switch (fall-through, non-exhaustive)match (no fall-through, exhaustive)
std::visit + overloaded lambdasmatch
nullptr, std::optional<T>Option<T>, free for pointers
Structured bindingsPatterns in let, match, if let, for, parameters

Exercises

  1. Add a Dispatch variant to Command and handle it in execute.
  2. Write impl TryFrom<u32> for BlendMode that maps 0, 1, 2 to the variants and returns Err(value) otherwise.
  3. Model a door with states Closed, Opening { progress: f32 }, Open and Closing { progress: f32 }, and write fn update(self, dt: f32) -> DoorState that advances the state machine.

Error handling

C++ has too many ways to report an error: exceptions, error codes, errno, HRESULT, VkResult, std::error_code, std::expected, bool plus an out parameter, and assert. Engines usually ban exceptions and end up with a mix of the rest. Rust has two mechanisms with a clear division of labor:

  • Result<T, E> for errors a caller can reasonably handle: a missing file, a malformed asset, a device that failed to initialize. It is an ordinary return value, as cheap as an error code.
  • panic! for bugs: a broken invariant, an out-of-bounds index, an unwrap() on something that was supposed to be there. It is like a failed assert that stays on in release builds.

This chapter covers both, the ? operator that makes Result pleasant, how to define error types, and wrapping C error codes.

Result<T, E>

Result is an enum from the standard library:

enum Result<T, E> {
    Ok(T),
    Err(E),
}
fn main() {}

A function that can fail returns it, and the caller must look at it to get the value out. There is no way to accidentally ignore the error and use the garbage value, which is the classic bug with error codes and out parameters.

use std::fs;
use std::io;

fn read_shader(path: &str) -> Result<String, io::Error> {
    fs::read_to_string(path)
}

fn main() {
    match read_shader("shaders/missing.glsl") {
        Ok(src) => println!("{} bytes", src.len()),
        Err(e) => println!("could not load shader: {e}"),
    }
}

The compiler also warns if you call a function returning Result and drop the result on the floor (Result is marked #[must_use], the equivalent of [[nodiscard]]).

The ? operator

Checking every call by hand would be as tedious as checking every VkResult. The ? operator does it for you: on Ok(v) it evaluates to v; on Err(e) it returns early from the current function with that error, converting it to the function's error type if needed.

C++ with error codes

VkResult create_renderer(Renderer* out) {
    VkResult r;
    r = create_instance(&out->instance);
    if (r != VK_SUCCESS) return r;
    r = pick_device(out->instance, &out->device);
    if (r != VK_SUCCESS) return r;
    r = create_swapchain(out->device, &out->swapchain);
    if (r != VK_SUCCESS) return r;
    return VK_SUCCESS;
}

Rust with ?

struct Instance; struct Device; struct Swapchain;
struct Renderer { instance: Instance, device: Device, swapchain: Swapchain }
#[derive(Debug)] struct GfxError;
fn create_instance() -> Result<Instance, GfxError> { Ok(Instance) }
fn pick_device(_: &Instance) -> Result<Device, GfxError> { Ok(Device) }
fn create_swapchain(_: &Device) -> Result<Swapchain, GfxError> { Ok(Swapchain) }
fn create_renderer() -> Result<Renderer, GfxError> {
    let instance = create_instance()?;
    let device = pick_device(&instance)?;
    let swapchain = create_swapchain(&device)?;
    Ok(Renderer { instance, device, swapchain })
}
fn main() { create_renderer().unwrap(); }

The control flow is identical to the C++ version: every ? is an early return. It is just visible as one character instead of three lines. Unlike exceptions, there is no hidden path out of a function; every place that can return an error is marked with ?.

? also works on Option in functions that return Option, returning None early.

Defining error types

For a library, define an enum of the things that can go wrong, implement Display for messages and std::error::Error so it composes with other errors. Implement From for the underlying errors and ? converts them automatically:

use std::fmt;
use std::num::ParseIntError;

#[derive(Debug)]
enum ObjError {
    Io(std::io::Error),
    BadNumber { line: usize, source: ParseIntError },
    UnknownDirective { line: usize, text: String },
}

impl fmt::Display for ObjError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ObjError::Io(e) => write!(f, "I/O error: {e}"),
            ObjError::BadNumber { line, source } => write!(f, "line {line}: {source}"),
            ObjError::UnknownDirective { line, text } => write!(f, "line {line}: unknown `{text}`"),
        }
    }
}

impl std::error::Error for ObjError {}

impl From<std::io::Error> for ObjError {
    fn from(e: std::io::Error) -> Self {
        ObjError::Io(e)
    }
}

/// Count faces in a tiny subset of the OBJ format.
fn count_faces(text: &str) -> Result<usize, ObjError> {
    let mut faces = 0;
    for (i, line) in text.lines().enumerate() {
        let mut parts = line.split_whitespace();
        match parts.next() {
            None | Some("#") | Some("v") | Some("vn") => {}
            Some("f") => {
                for p in parts {
                    let idx = p.split('/').next().unwrap_or("");
                    idx.parse::<u32>()
                        .map_err(|source| ObjError::BadNumber { line: i + 1, source })?;
                }
                faces += 1;
            }
            Some(other) => {
                return Err(ObjError::UnknownDirective { line: i + 1, text: other.to_string() })
            }
        }
    }
    Ok(faces)
}

fn main() {
    println!("{:?}", count_faces("v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n").map_err(|e| e.to_string()));
    match count_faces("v 0 0 0\nf 1 x 3\n") {
        Ok(n) => println!("{n} faces"),
        Err(e) => println!("error: {e}"),
    }
    if let Err(e) = count_faces("usemtl brick\n") {
        println!("error: {e}");
    }
}

That is a lot of boilerplate, and in practice two crates remove it:

  • thiserror for libraries: #[derive(thiserror::Error)] with #[error("line {line}: {source}")] attributes generates the Display, Error and From implementations above.
  • anyhow for applications: anyhow::Result<T> holds any error, and .context("loading level")? adds a human-readable layer, so the final message reads like a stack of reasons ("loading level: reading mesh.obj: file not found").

A good rule: libraries return precise error enums so callers can react to specific cases; applications collect errors with anyhow and report them.

// An application using anyhow (not runnable here: it needs the crate)
use anyhow::{Context, Result};

fn load_level(name: &str) -> Result<Level> {
    let path = format!("levels/{name}.ron");
    let text = std::fs::read_to_string(&path)
        .with_context(|| format!("reading {path}"))?;
    let level = parse_level(&text).context("parsing level")?;
    Ok(level)
}

fn main() -> Result<()> {
    let level = load_level("e1m1")?;  // main can return Result: errors are printed
    run(level)
}

Panics

A panic means "this is a bug; stop". panic!("..."), unreachable!(), assert!(cond), an out-of-bounds index, integer overflow in debug builds and unwrap() on None/Err all panic.

By default a panic unwinds the stack of the current thread, running Drop for everything on the way, like an exception that nobody catches. If it reaches the top of main, the program exits with an error message. If it happens on another thread, that thread dies and join() returns an error. With panic = "abort" in the profile, a panic aborts the process immediately instead, which is what most game builds want: smaller binaries, no unwinding tables, and a crash dump at the exact point of failure.

C++ habit to unlearn

A panic is not an exception to be caught and recovered from. Do not use it for expected failures, and do not structure code around catching it (std::panic::catch_unwind exists for FFI boundaries and thread pools, not for control flow). Expected failure is Result; a panic is an assert.

When is unwrap() acceptable?

  • In tests, examples and prototypes.
  • When the invariant is guaranteed by your own code just above, and an error would be a bug. Prefer expect("why this cannot fail"), which documents the reason and appears in the panic message.
  • At startup, for resources the program truly cannot run without, although returning an error from main gives a nicer message.

Wrapping C error codes

C APIs report errors as integers. Convert them at the boundary, once, so the rest of the code works with Result:

// Pretend these come from a C header via bindgen.
#[allow(non_camel_case_types)]
type VkResult = i32;
const VK_SUCCESS: VkResult = 0;
const VK_ERROR_OUT_OF_DEVICE_MEMORY: VkResult = -2;
const VK_ERROR_DEVICE_LOST: VkResult = -4;

#[derive(Debug, PartialEq)]
enum VkError {
    OutOfDeviceMemory,
    DeviceLost,
    Other(i32),
}

fn check(r: VkResult) -> Result<(), VkError> {
    match r {
        VK_SUCCESS => Ok(()),
        VK_ERROR_OUT_OF_DEVICE_MEMORY => Err(VkError::OutOfDeviceMemory),
        VK_ERROR_DEVICE_LOST => Err(VkError::DeviceLost),
        other => Err(VkError::Other(other)),
    }
}

fn allocate(size: u64) -> Result<u64, VkError> {
    let r = if size > 1 << 30 { VK_ERROR_OUT_OF_DEVICE_MEMORY } else { VK_SUCCESS }; // the "C call"
    check(r)?;
    Ok(0xdead_0000)
}

fn main() {
    println!("{:?}", allocate(256));
    println!("{:?}", allocate(4 << 30));
}

The ash crate does this for all of Vulkan: every function returns VkResult<T>, a Result<T, vk::Result>. See the Vulkan chapter.

Summary

C++Rust
Exceptions for recoverable errorsResult<T, E> and ?
Error codes + out parametersResult<T, E>
[[nodiscard]]#[must_use] (on Result by default)
std::expected<T, E> (C++23)Result<T, E>
assert, std::terminateassert!, panic!, unwrap(), expect()
-fno-exceptionspanic = "abort"
Custom exception hierarchyError enum + std::error::Error (thiserror)
Catch-all error reportinganyhow::Error with .context()

Exercises

  1. Change count_faces to also accept vt lines, and to reject faces with fewer than three vertices with a new ObjError variant.
  2. Write fn parse_resolution(s: &str) -> Result<(u32, u32), String> for input like "1920x1080", using ? and map_err.
  3. Make main return Result<(), Box<dyn std::error::Error>> and use ? on a file read. What gets printed when the file does not exist?

Traits and generics

C++ gives you two separate tools for polymorphism: virtual functions for run-time dispatch and templates for compile-time dispatch, with concepts (C++20) bolted on to constrain templates. Rust has one concept that serves both purposes: the trait. A trait is a set of methods a type can implement. Used as a constraint on a generic, it is a concept and the call is resolved at compile time. Used behind a pointer as dyn Trait, it is an interface with a vtable.

This chapter covers:

  • defining and implementing traits,
  • generics with trait bounds, and how they compare to templates and concepts,
  • dyn Trait and where the vtable pointer lives,
  • choosing between static and dynamic dispatch,
  • associated types and constants,
  • composition instead of inheritance,
  • the orphan rule.

Defining and implementing a trait

trait Shape {
    fn area(&self) -> f32;
    fn name(&self) -> String {               // a default method, like a non-pure virtual
        String::from("shape")
    }
}

struct Circle {
    r: f32,
}

struct Rect {
    w: f32,
    h: f32,
}

impl Shape for Circle {
    fn area(&self) -> f32 {
        std::f32::consts::PI * self.r * self.r
    }
    fn name(&self) -> String {
        format!("circle r={}", self.r)
    }
}

impl Shape for Rect {
    fn area(&self) -> f32 {
        self.w * self.h
    }
}

fn main() {
    let c = Circle { r: 1.0 };
    let r = Rect { w: 2.0, h: 3.0 };
    println!("{} {}", c.name(), c.area());
    println!("{} {}", r.name(), r.area());
}

The implementation is separate from the type: impl Shape for Circle can live next to the trait, next to the type, or anywhere else in the crate. You can implement your own traits for types you did not write, including i32, Vec<T> and types from other crates. That is impossible with C++ base classes, which must be decided when the class is defined.

Generics: compile-time polymorphism

A generic function has type parameters, like a template. Unlike a template, the parameters must be bounded by the traits the body uses:

C++ template (unconstrained)

template <typename S>
float total_area(const std::vector<S>& shapes) {
    float sum = 0;
    for (const auto& s : shapes)
        sum += s.area();   // checked only when instantiated
    return sum;
}

Rust generic (bounded)

trait Shape { fn area(&self) -> f32; }
fn total_area<S: Shape>(shapes: &[S]) -> f32 {
    let mut sum = 0.0;
    for s in shapes {
        sum += s.area();   // allowed: S: Shape
    }
    sum
}
fn main() {}

The bound S: Shape is a contract checked in both directions:

  • At the definition, the body may only use what the bounds promise. Calling s.perimeter() inside total_area is an error right there, even if no one calls total_area yet. C++ templates are checked only when instantiated, and even concepts do not stop a template body from using operations its concept does not mention.
  • At the call site, the argument type must implement Shape. The error says "the trait Shape is not implemented for Triangle", not three pages of substitution failures.

Code generation works exactly like templates: the compiler monomorphizes, creating a separate copy of total_area for each concrete S, with area() calls resolved statically and usually inlined. There is no run-time cost.

Bounds can be written several ways; they all mean the same:

use std::fmt::Debug;

trait Shape { fn area(&self) -> f32; }

fn a<S: Shape + Debug>(s: &S) -> f32 { s.area() }              // inline bounds
fn b<S>(s: &S) -> f32 where S: Shape + Debug { s.area() }      // where clause
fn c(s: &(impl Shape + Debug)) -> f32 { s.area() }              // impl Trait in argument position

// Returning `impl Trait`: "some concrete type that implements Iterator",
// like returning `auto` from a function, but with a stated interface.
fn evens(limit: u32) -> impl Iterator<Item = u32> {
    (0..limit).filter(|n| n % 2 == 0)
}

fn main() {
    println!("{:?}", evens(10).collect::<Vec<_>>());
}

Generic structs work like class templates:

#[derive(Debug, Clone, Copy, PartialEq)]
struct Rect<T> {
    min: [T; 2],
    max: [T; 2],
}

impl<T: Copy + PartialOrd> Rect<T> {
    fn contains(&self, p: [T; 2]) -> bool {
        p[0] >= self.min[0] && p[0] < self.max[0] && p[1] >= self.min[1] && p[1] < self.max[1]
    }
}

// Methods that exist only for one instantiation, like a partial specialization of the interface.
impl Rect<f32> {
    fn area(&self) -> f32 {
        (self.max[0] - self.min[0]) * (self.max[1] - self.min[1])
    }
}

fn main() {
    let pixels = Rect { min: [0u32, 0], max: [1920, 1080] };
    let uv = Rect { min: [0.0f32, 0.0], max: [0.5, 0.5] };
    println!("{} {} {}", pixels.contains([10, 10]), uv.contains([0.7, 0.1]), uv.area());
}

Rust has no template specialization (an unstable version exists), no variadic generics, and no SFINAE. Const generics (struct Matrix<const R: usize, const C: usize>) cover the most common use of non-type template parameters.

dyn Trait: run-time polymorphism

To hold different shapes in one collection, you need dynamic dispatch. In Rust that is a trait object, dyn Shape, always used behind a pointer: &dyn Shape, Box<dyn Shape>, Arc<dyn Shape>.

trait Shape {
    fn area(&self) -> f32;
}
struct Circle { r: f32 }
struct Rect { w: f32, h: f32 }
impl Shape for Circle { fn area(&self) -> f32 { 3.14159 * self.r * self.r } }
impl Shape for Rect { fn area(&self) -> f32 { self.w * self.h } }

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![
        Box::new(Circle { r: 1.0 }),
        Box::new(Rect { w: 2.0, h: 3.0 }),
    ];
    let total: f32 = shapes.iter().map(|s| s.area()).sum();
    println!("{total}");
    println!("Box<dyn Shape> is {} bytes", std::mem::size_of::<Box<dyn Shape>>());
    println!("Circle is {} bytes", std::mem::size_of::<Circle>());
}

The output shows something surprising: a Box<dyn Shape> is two pointers wide, and a Circle is just its f32. Rust does not store a vtable pointer in the object. It stores it in the pointer. Step through the comparison:

Consequences of storing the vtable in a "fat pointer":

  • Types pay nothing for traits they might be used through. A Vec3 can implement ten traits and still be 12 bytes, usable in a GPU buffer.
  • The same object can be viewed through different traits at different times, each with its own vtable.
  • You can make a trait object out of any type, including i32 or a type from another crate, without changing it.
  • Each &dyn Trait is 16 bytes instead of 8. Arrays of trait objects cost twice the pointer memory.

Not every trait can be used as dyn. A trait is dyn-compatible (formerly "object safe") if its methods can be called through a vtable: no generic methods, and no methods returning Self by value. The compiler tells you when a trait is not.

Static or dynamic dispatch?

Generics (T: Trait)Trait objects (dyn Trait)
C++ analogueTemplates + conceptsVirtual functions
DispatchCompile time; inlinableRun time; indirect call
Code sizeOne copy per typeOne copy
Heterogeneous collectionsNoYes
Compile timeLongerShorter

Rust code defaults to generics, as modern C++ defaults to templates in libraries. Reach for dyn when you need a heterogeneous collection, a plugin boundary, or to stop generic code from spreading through a large codebase.

Engine note

The classic OOP engine has class GameObject { virtual void update(); } and a std::vector<GameObject*>. The direct translation, Vec<Box<dyn GameObject>>, works and is sometimes right (a few dozen heterogeneous systems, editor panels, a render-graph's passes). For thousands of entities it has the same cache problems as in C++, plus it fights the borrow checker as soon as objects need to touch each other. Most Rust engines use enums for closed sets of variants (Enums) and an ECS for game objects (ECS chapter).

Associated types and constants

Traits can declare types and constants that each implementation fills in, much like nested typedefs in a C++ traits class:

trait VertexFormat {
    type Index;                  // associated type
    const STRIDE: usize;         // associated constant
    fn attributes() -> &'static [(&'static str, usize)];
}

#[repr(C)]
struct PosUv {
    pos: [f32; 3],
    uv: [f32; 2],
}

impl VertexFormat for PosUv {
    type Index = u16;
    const STRIDE: usize = std::mem::size_of::<PosUv>();
    fn attributes() -> &'static [(&'static str, usize)] {
        &[("pos", 0), ("uv", 12)]
    }
}

fn describe<V: VertexFormat>() {
    println!(
        "stride {} bytes, index {} bytes, attributes {:?}",
        V::STRIDE,
        std::mem::size_of::<V::Index>(),
        V::attributes()
    );
}

fn main() {
    describe::<PosUv>();
}

The standard library's Iterator trait has an associated type Item, which is why you write impl Iterator<Item = u32>.

Composition instead of inheritance

Rust has no struct inheritance. What it offers instead:

  • Composition: a struct contains other structs as fields, and forwards methods explicitly where needed.
  • Default methods on traits provide shared behavior.
  • Supertraits: trait Drawable: Shape means every Drawable is also a Shape, so code with a Drawable can call area(). This is interface inheritance, not data inheritance.
  • Blanket implementations: implement a trait for every type that satisfies some bound, e.g. impl<T: Shape> Describe for T { ... }.
trait Shape {
    fn area(&self) -> f32;
}

trait Describe {
    fn describe(&self) -> String;
}

// Every Shape gets Describe for free.
impl<T: Shape> Describe for T {
    fn describe(&self) -> String {
        format!("a shape with area {:.2}", self.area())
    }
}

struct Square(f32);
impl Shape for Square {
    fn area(&self) -> f32 { self.0 * self.0 }
}

fn main() {
    println!("{}", Square(3.0).describe());
}
C++ habit to unlearn

Do not try to emulate a class hierarchy with traits and Deref. If you catch yourself designing trait Entity, trait Actor: Entity, trait Pawn: Actor, step back. Ask which behaviors you need to abstract over (update, render, serialize), make those small traits, and let concrete types compose data.

The orphan rule

You may write impl Trait for Type only if your crate defines the trait or the type (or both). You cannot implement std::fmt::Display for Vec<u8>, because neither is yours. This coherence rule guarantees there is at most one implementation of a trait for a type in the whole program, so adding a dependency can never make two implementations clash, the way two libraries' operator<< overloads or template specializations can in C++.

The usual workaround is a newtype: struct Bytes(Vec<u8>); is your type, so you may implement anything for it.

Summary

C++Rust
Abstract base classTrait
Virtual functionTrait method called through dyn Trait
vptr inside the objectVtable pointer inside a fat pointer
TemplateGeneric with trait bounds
ConceptTrait bound, checked at definition and use
auto f() returning a hidden typefn f() -> impl Trait
Traits class / nested typedefAssociated type / constant
Inheritance of dataComposition
Template specializationNot available (use traits on concrete types)

Exercises

  1. Add a perimeter method to Shape without a default, and fix the compile errors. Then give it a default that returns 0.0 and remove one implementation. What changes?
  2. Write fn largest<T: PartialOrd + Copy>(xs: &[T]) -> Option<T>. Call it with i32s, f32s and chars. Why does Copy appear in the bound?
  3. Write a trait System { fn run(&mut self, dt: f32); } and store three different systems in a Vec<Box<dyn System>>. Then rewrite it with an enum of the three systems. Which would you choose for 3 systems, and for 300?

Operator overloading and conversions

C++ lets you overload almost any operator and define implicit conversions in two directions (converting constructors and conversion operators). Rust allows overloading a fixed set of operators through traits, and has no implicit conversions between your types at all. Every conversion is a named call. The result is a little more typing and much less surprise.

This chapter covers:

  • overloading arithmetic, indexing and compound assignment for a math type,
  • Copy and Clone in detail,
  • comparison traits, and why floats are awkward,
  • From, Into, TryFrom and AsRef in place of conversion constructors,
  • Deref, and why it is not a general conversion operator,
  • Display and Debug in place of operator<<.

Arithmetic operators

Each operator maps to a trait in std::ops. a + b is sugar for Add::add(a, b):

use std::ops::{Add, AddAssign, Index, IndexMut, Mul, Neg, Sub};

#[derive(Debug, Clone, Copy, PartialEq, Default)]
struct Vec3 {
    x: f32,
    y: f32,
    z: f32,
}

impl Vec3 {
    const fn new(x: f32, y: f32, z: f32) -> Self { Vec3 { x, y, z } }
    fn dot(self, o: Vec3) -> f32 { self.x * o.x + self.y * o.y + self.z * o.z }
}

impl Add for Vec3 {
    type Output = Vec3;
    fn add(self, o: Vec3) -> Vec3 { Vec3::new(self.x + o.x, self.y + o.y, self.z + o.z) }
}

impl Sub for Vec3 {
    type Output = Vec3;
    fn sub(self, o: Vec3) -> Vec3 { Vec3::new(self.x - o.x, self.y - o.y, self.z - o.z) }
}

impl Neg for Vec3 {
    type Output = Vec3;
    fn neg(self) -> Vec3 { Vec3::new(-self.x, -self.y, -self.z) }
}

// Vec3 * f32
impl Mul<f32> for Vec3 {
    type Output = Vec3;
    fn mul(self, s: f32) -> Vec3 { Vec3::new(self.x * s, self.y * s, self.z * s) }
}

// f32 * Vec3: the left operand's type picks the impl, so this needs its own.
impl Mul<Vec3> for f32 {
    type Output = Vec3;
    fn mul(self, v: Vec3) -> Vec3 { v * self }
}

impl AddAssign for Vec3 {
    fn add_assign(&mut self, o: Vec3) { *self = *self + o; }
}

impl Index<usize> for Vec3 {
    type Output = f32;
    fn index(&self, i: usize) -> &f32 {
        match i {
            0 => &self.x,
            1 => &self.y,
            2 => &self.z,
            _ => panic!("Vec3 index {i} out of range"),
        }
    }
}

impl IndexMut<usize> for Vec3 {
    fn index_mut(&mut self, i: usize) -> &mut f32 {
        match i {
            0 => &mut self.x,
            1 => &mut self.y,
            2 => &mut self.z,
            _ => panic!("Vec3 index {i} out of range"),
        }
    }
}

fn main() {
    let gravity = Vec3::new(0.0, -9.81, 0.0);
    let mut velocity = Vec3::new(1.0, 5.0, 0.0);
    let dt = 1.0 / 60.0;
    velocity += gravity * dt;
    let reflected = velocity - 2.0 * velocity.dot(Vec3::new(0.0, 1.0, 0.0)) * Vec3::new(0.0, 1.0, 0.0);
    velocity[0] = 0.5;
    println!("{velocity:?} {reflected:?} {}", -gravity[1]);
}

What you can overload: + - * / %, the bitwise operators & | ^ ! << >>, unary -, their compound-assignment forms (+= and so on), indexing [], and dereference * (through Deref, below). Comparisons come from PartialEq and PartialOrd.

What you cannot overload: &&, ||, assignment =, the comma, ->, new, function call () on your own types (closures fill that role), and conversion operators. There is no operator to overload for a copy, either: Copy types are always copied bit for bit.

Under the hood

Add takes self by value. For small Copy types like Vec3 that is ideal, since they are passed in registers. For large types (a 4x4 matrix is 64 bytes) it is common to also implement Add<&Mat4> for &Mat4 so &a + &b avoids copies, though in practice the optimizer usually removes them either way. Check the assembly before you complicate the API.

Copy and Clone

Ownership introduced these; here are the details:

  • Clone is an explicit, possibly expensive duplicate: let b = a.clone();. You can implement it by hand or derive it, which clones each field.
  • Copy is a marker that says "duplicating my bytes is a valid copy". It changes assignment and argument passing from a move to a copy. Copy requires Clone, and you cannot customize it: a Copy type's clone must be a plain bitwise copy.
  • A type can be Copy only if all its fields are Copy, and it does not implement Drop.

So a Rust Copy type is what C++ calls trivially copyable, and there is no way to write a type with an expensive implicit copy, like std::string. The copy-constructor bugs (slicing, accidental deep copies in a range-for, copying a std::vector into a lambda) do not have a Rust counterpart.

Comparisons

TraitOperatorsMeaning
PartialEq==, !=Equality that may not be reflexive (NaN != NaN)
Eq(none)Marker: equality is a true equivalence relation
PartialOrd<, <=, >, >=Ordering where some pairs are incomparable
Ord(none)Marker + cmp: a total order
Hash(none)Hashing consistent with Eq

#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)] compares field by field in declaration order, like C++20's defaulted operator<=>.

The split exists because of floating point. f32 is PartialEq and PartialOrd but not Eq or Ord, so APIs that need a total order reject it:

fn main() {
    let mut depths = vec![3.5f32, -1.0, 2.25, 0.0];
    // depths.sort();                        // error: f32 is not Ord
    depths.sort_by(|a, b| a.total_cmp(b));   // IEEE totalOrder: NaNs sort to the ends
    println!("{depths:?}");

    let closest = depths.iter().copied().fold(f32::INFINITY, f32::min);
    println!("{closest}");

    // Hashing floats: store the bits, deciding explicitly what -0.0 and NaN mean.
    use std::collections::HashSet;
    let set: HashSet<u32> = depths.iter().map(|d| d.to_bits()).collect();
    println!("{} unique depths", set.len());
}

In C++ sorting a std::vector<float> containing a NaN with std::sort is undefined behavior (it breaks the strict weak ordering requirement). In Rust the type system makes you choose.

Conversions: From, Into, TryFrom

C++ conversions are often implicit: a single-argument constructor converts unless marked explicit, and operator T() converts out. Rust replaces all of that with traits you call by name:

use std::convert::TryFrom;

#[derive(Debug, Clone, Copy)]
struct Rgba8([u8; 4]);

#[derive(Debug, Clone, Copy)]
struct LinearColor { r: f32, g: f32, b: f32, a: f32 }

// From: an infallible conversion. Implementing it gives you Into for free.
impl From<Rgba8> for LinearColor {
    fn from(c: Rgba8) -> Self {
        let f = |v: u8| (v as f32 / 255.0).powf(2.2);
        LinearColor { r: f(c.0[0]), g: f(c.0[1]), b: f(c.0[2]), a: c.0[3] as f32 / 255.0 }
    }
}

// TryFrom: a conversion that can fail.
impl TryFrom<&str> for Rgba8 {
    type Error = String;
    fn try_from(hex: &str) -> Result<Self, Self::Error> {
        let hex = hex.strip_prefix('#').ok_or("missing #")?;
        if hex.len() != 8 {
            return Err(format!("expected 8 hex digits, got {}", hex.len()));
        }
        let mut out = [0u8; 4];
        for i in 0..4 {
            out[i] = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).map_err(|e| e.to_string())?;
        }
        Ok(Rgba8(out))
    }
}

fn set_clear_color(c: impl Into<LinearColor>) {
    let c: LinearColor = c.into();
    println!("clear {c:?}");
}

fn main() {
    let orange = Rgba8::try_from("#ff8000ff").unwrap();
    let linear = LinearColor::from(orange);   // explicit
    let also: LinearColor = orange.into();     // same thing, type from context
    set_clear_color(orange);                   // generic over anything convertible
    println!("{linear:?} {also:?} {:?}", Rgba8::try_from("ff8000"));
}

Taking impl Into<T> in a parameter is the Rust way to get the convenience of an implicit conversion: callers can pass either a T or anything that converts to one. It is still visible in the signature.

Other common conversion traits:

TraitUse
AsRef<T>Cheap reference conversion: fn open(p: impl AsRef<Path>) accepts &str, String, PathBuf…
Borrow<T>Like AsRef, used by HashMap::get so a HashMap<String, _> can be queried with &str
ToOwnedBorrowed to owned: &str → String, &[T] → Vec<T>
FromStrParsing: "42".parse::<i32>()
DefaultA default value, like a default constructor

Deref: smart pointers, not conversions

Deref overloads unary * and lets method calls see through a wrapper. It is how Box<T>, Rc<T>, String (to str) and Vec<T> (to [T]) work:

use std::ops::Deref;

/// A Vec that is guaranteed to be sorted.
struct SortedVec(Vec<i32>);

impl SortedVec {
    fn new(mut v: Vec<i32>) -> Self {
        v.sort();
        SortedVec(v)
    }
}

impl Deref for SortedVec {
    type Target = [i32];      // read-only access to the elements as a slice
    fn deref(&self) -> &[i32] {
        &self.0
    }
}

fn main() {
    let s = SortedVec::new(vec![5, 1, 4]);
    println!("{} {:?} {:?}", s.len(), s.first(), s.binary_search(&4)); // slice methods
}

Note what is not implemented: DerefMut. Users can read the slice but cannot get a &mut [i32] and break the sorted invariant.

When the compiler sees &SortedVec where &[i32] is expected, it inserts the deref call (deref coercion). That is the only implicit conversion in Rust, and it applies only to references. Use Deref for pointer-like wrappers. Do not use it to fake inheritance (struct Player { base: Entity } with Deref<Target = Entity>): it confuses readers and stops working as soon as you need trait implementations.

Display and Debug instead of operator<<

Printing is two traits:

  • Debug ({:?}, pretty-printed with {:#?}) is for developers. Derive it on almost every type.
  • Display ({}) is for users. Implement it by hand when a type has a natural textual form.
use std::fmt;

#[derive(Debug)]
struct Mat2([[f32; 2]; 2]);

impl fmt::Display for Mat2 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let p = f.precision().unwrap_or(2);   // honor {:.3}
        for row in &self.0 {
            writeln!(f, "[{:>8.p$} {:>8.p$}]", row[0], row[1], p = p)?;
        }
        Ok(())
    }
}

fn main() {
    let m = Mat2([[1.0, 0.5], [-0.25, 2.0]]);
    print!("{m}");
    print!("{m:.4}");
    println!("{m:?}");
}

Implementing Display also gives you .to_string() for free.

Summary

C++Rust
operator+ member or free functionimpl Add for T
operator+=impl AddAssign for T
operator[]Index / IndexMut
Copy constructorClone (explicit); Copy (bitwise, implicit)
operator==, operator<=>PartialEq/Eq, PartialOrd/Ord, usually derived
Converting constructorFrom / Into (explicit call)
explicit constructor that can failTryFrom
operator T()Not available; implement From<YourType> for T
operator*, operator-> on smart pointersDeref / DerefMut
operator<<(std::ostream&, …)Display, Debug

Exercises

  1. Add Div<f32>, Sub-assign and a normalize method to Vec3, and make normalize return Option<Vec3> for a zero vector.
  2. Implement Mul<Vec3> for Mat3 (a 3x3 matrix as [[f32; 3]; 3]) and Mul<Mat3> for Mat3.
  3. Implement FromStr for Rgba8 so "#ff8000ff".parse::<Rgba8>() works, reusing the TryFrom implementation.

Collections and strings

Rust's standard collections cover the STL containers you use daily, with the same complexity guarantees and similar memory layouts. The differences are in the API: no iterator pairs, no invalidation bugs, explicit capacity management, and strings that are always UTF-8.

This chapter covers:

  • Vec<T> and slices,
  • HashMap, BTreeMap, HashSet, VecDeque and BinaryHeap,
  • the entry API,
  • String and &str, and why strings are not arrays of characters,
  • other string types: OsString, CString, Path,
  • choosing containers for engine workloads.

The mapping

STLRustNotes
std::vector<T>Vec<T>Same layout: pointer, capacity, length
std::array<T, N>[T; N]Built-in type
std::span<T>&[T] / &mut [T]Built-in slice type
std::deque<T>VecDeque<T>A ring buffer, not chunked like std::deque
std::list<T>LinkedList<T>Exists; almost never the right choice
std::unordered_map<K, V>HashMap<K, V>Open addressing (SwissTable), much faster than node-based unordered_map
std::unordered_set<T>HashSet<T>
std::map<K, V>BTreeMap<K, V>A B-tree, not a red-black tree: better cache behavior
std::set<T>BTreeSet<T>
std::priority_queue<T>BinaryHeap<T>Max-heap
std::stringStringUTF-8
std::string_view&str

All of these live in std::collections except Vec, String and slices, which are always in scope.

Vec<T>

fn main() {
    let mut particles: Vec<[f32; 3]> = Vec::with_capacity(1024); // reserve up front
    for i in 0..4 {
        particles.push([i as f32, 0.0, 0.0]);
    }
    println!("len {} cap {}", particles.len(), particles.capacity());

    let last = particles.pop();                 // Option<[f32; 3]>
    particles.insert(0, [9.0; 3]);              // O(n), like vector::insert
    particles.swap_remove(1);                   // O(1): move the last element into the hole
    particles.retain(|p| p[0] < 5.0);           // erase-remove idiom in one call
    particles.extend([[7.0; 3], [8.0; 3]]);
    particles.sort_by(|a, b| a[0].total_cmp(&b[0]));
    particles.dedup();
    println!("{particles:?} popped {last:?}");

    let first_two = &particles[..2];            // a slice borrowing from the Vec
    let total: f32 = first_two.iter().map(|p| p[0]).sum();
    println!("{total}");

    particles.clear();                          // len 0, capacity kept
    particles.shrink_to_fit();
}

Things that differ from std::vector:

  • Elements move with memcpy on reallocation; there are no move constructors to call and no noexcept question.
  • Indexing is bounds-checked and panics when out of range. Use .get(i) for an Option, or iterate to avoid checks entirely. get_unchecked exists but is unsafe.
  • No invalidation bugs: while you hold a reference into a Vec, the compiler will not let you push to it (Borrowing).
  • Vec<bool> is a normal vector of bytes. There is no bit-packing special case.
  • vec![value; n] and vec![a, b, c] build vectors inline.

Most of the useful algorithms are methods on slices, so they work on Vec, arrays and sub-ranges alike: sort, sort_unstable, binary_search, contains, iter().position, chunks, windows, split_at, rotate_left, fill, copy_from_slice, reverse.

Maps and sets

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

fn main() {
    let mut textures: HashMap<String, u32> = HashMap::new();
    textures.insert("brick".to_string(), 1);
    textures.insert("grass".to_string(), 2);

    // Lookup with &str even though keys are String (via the Borrow trait).
    if let Some(id) = textures.get("brick") {
        println!("brick is texture {id}");
    }
    println!("{:?}", textures.get("lava"));   // None, no default-constructed insert

    // The entry API: find-or-insert in one hash lookup.
    let mut refcounts: HashMap<&str, u32> = HashMap::new();
    for name in ["brick", "grass", "brick", "brick"] {
        *refcounts.entry(name).or_insert(0) += 1;
    }
    println!("{refcounts:?}");

    // Ordered map: iteration is sorted by key.
    let mut by_depth: BTreeMap<u32, Vec<&str>> = BTreeMap::new();
    by_depth.entry(3).or_default().push("tree");
    by_depth.entry(1).or_default().push("sky");
    by_depth.entry(3).or_default().push("rock");
    for (depth, names) in &by_depth {
        println!("{depth}: {names:?}");
    }
    // Range queries, like lower_bound/upper_bound:
    let near: Vec<_> = by_depth.range(..3).collect();
    println!("{near:?}");

    let visible: HashSet<u32> = [1, 2, 3].into_iter().collect();
    let lit: HashSet<u32> = [2, 3, 4].into_iter().collect();
    let both: Vec<_> = visible.intersection(&lit).collect();
    println!("{both:?}");
}
C++ habit to unlearn

map[key] in C++ inserts a default value when the key is missing. In Rust, map[&key] panics when the key is missing, and there is no implicit insert. Use get to look up, entry(key).or_default() to find-or-insert, and insert to overwrite.

The default HashMap uses SipHash, which resists denial-of-service attacks from attacker-chosen keys but is slower than necessary for integer keys in a game. Swap the hasher with a crate like rustc-hash (FxHashMap) or ahash when the keys are trusted:

use rustc_hash::FxHashMap;
let mut by_entity: FxHashMap<u32, Transform> = FxHashMap::default();

VecDeque and BinaryHeap

use std::cmp::Reverse;
use std::collections::{BinaryHeap, VecDeque};

fn main() {
    // A ring buffer: frame-time history.
    let mut frame_times: VecDeque<f32> = VecDeque::with_capacity(4);
    for t in [16.6, 16.7, 33.3, 16.5, 16.8] {
        if frame_times.len() == 4 {
            frame_times.pop_front();
        }
        frame_times.push_back(t);
    }
    println!("{frame_times:?}");

    // A min-heap of (cost, node) for Dijkstra / A*: wrap in Reverse.
    let mut open = BinaryHeap::new();
    open.push(Reverse((5u32, "b")));
    open.push(Reverse((1, "a")));
    open.push(Reverse((3, "c")));
    while let Some(Reverse((cost, node))) = open.pop() {
        print!("{node}:{cost} ");
    }
    println!();
}

Strings

Rust has two main string types:

  • String: owned, growable, heap-allocated. Like std::string.
  • &str: a borrowed view of string data, a pointer and a length. Like std::string_view. String literals are &'static str.

Both are always valid UTF-8. The compiler and the standard library enforce it: every function that creates a String from bytes either validates them or is unsafe.

fn shout(s: &str) -> String {          // take &str, return String: the usual pattern
    s.to_uppercase()
}

fn main() {
    let mut log = String::from("frame ");
    log.push_str("42");
    log += ": ok";
    let summary = format!("{log} ({} bytes)", log.len());

    let name: &str = "Ünïcödé";
    println!("{summary}");
    println!("{} bytes, {} chars", name.len(), name.chars().count());
    // let c = name[0];            // error: strings cannot be indexed by integer
    println!("{:?}", name.chars().nth(1));
    println!("{}", &name[0..2]);   // byte range: must fall on char boundaries, or it panics
    println!("{}", shout("hello"));

    for word in "load mesh  brick.obj".split_whitespace() {
        print!("[{word}]");
    }
    println!();
    let path = "assets/textures/brick.png";
    if let Some((dir, file)) = path.rsplit_once('/') {
        println!("{dir} | {file} | {}", file.ends_with(".png"));
    }
}

Why no s[i]? Because in UTF-8 a character is one to four bytes, so "the i-th character" is an O(n) scan and "the i-th byte" may be half a character. Rust makes you say which you mean: s.as_bytes()[i] for bytes, s.chars() for Unicode scalar values. For ASCII-only data (like many file formats), work on &[u8] and byte literals b"...".

Take &str in function parameters, not &String: a &String coerces to &str automatically, and literals are already &str.

Under the hood

String is literally a Vec<u8> with a UTF-8 guarantee: pointer, capacity, length, 24 bytes. There is no small-string optimization, so every non-empty String allocates. If you build many tiny strings (entity names, debug labels), consider interning them into IDs, or crates like smol_str or compact_str.

Other string types

Text from the operating system or a C API is not necessarily UTF-8, so it has its own types:

TypeOwnedUse
&strStringRust text, always UTF-8
&OsStrOsStringPlatform strings: environment variables, OS APIs (UTF-16 on Windows)
&PathPathBufFile paths; a thin wrapper over OsStr with path methods
&CStrCStringNUL-terminated C strings for FFI
&[u8]Vec<u8>Raw bytes
use std::ffi::CString;
use std::path::{Path, PathBuf};

fn main() {
    let mut p = PathBuf::from("assets");
    p.push("shaders");
    p.push("lit.frag");
    println!("{} ext={:?} stem={:?}", p.display(), p.extension(), p.file_stem());
    println!("{}", Path::new("a/b/../c.txt").parent().unwrap().display());

    let name = CString::new("u_model_matrix").unwrap(); // adds the NUL, rejects interior NULs
    let ptr: *const std::ffi::c_char = name.as_ptr();    // what glGetUniformLocation wants
    println!("{ptr:?}");
}

Containers for engine workloads

  • Vec<T> first. As in C++, a contiguous array beats everything for iteration. Use swap_remove for O(1) unordered removal.
  • Fixed capacity, no heap: [T; N] plus a length, or the arrayvec crate.
  • Usually small, sometimes big: smallvec::SmallVec<[T; 8]> stores up to eight elements inline, like LLVM's SmallVector.
  • Stable handles into a growing pool: a slot map or generational arena (Handles and arenas).
  • Integer keys: FxHashMap, or a plain Vec<Option<T>> indexed by ID when IDs are dense.
  • Per-frame scratch memory: a bump allocator (bumpalo), reset each frame.

Summary

C++Rust
v[i] (unchecked) / v.at(i)v[i] (checked, panics) / v.get(i) (Option)
v.reserve(n)Vec::with_capacity(n) / v.reserve(n)
Erase-remove idiomv.retain(...)
map[key] insertsmap.entry(key).or_default(); map[&key] panics if missing
map.find(k) != map.end()map.get(&k) returns Option
std::string (bytes, any encoding)String (UTF-8)
s[i]s.as_bytes()[i] or s.chars().nth(i)
std::filesystem::pathPathBuf / &Path
c_str()CString::new(..)?.as_ptr()

Exercises

  1. Count word frequencies in a paragraph with a HashMap<&str, usize> and the entry API, then print the five most common words sorted by count.
  2. Write fn split_extension(path: &str) -> (&str, Option<&str>) that returns the path without its extension and the extension. What lifetime do the returned slices have?
  3. Implement a fixed-size ring buffer of the last 120 frame times with VecDeque, and compute the average and the 99th percentile.

Closures and iterators

Rust code uses closures and iterator chains where C++ uses raw loops, <algorithm> and (in C++20) ranges. Engine programmers are rightly suspicious of this style in C++, where it can hide allocations and defeat the optimizer in debug builds. In Rust it is the idiomatic style, and in optimized builds it compiles to the same loop you would write by hand. This chapter shows how closures capture, how iterators work, and how to confirm the cost yourself.

Closures

A closure is an anonymous function that can capture variables from its environment, like a C++ lambda:

C++

float scale = 2.0f;
auto f = [scale](float x) { return x * scale; };
auto g = [&count](int) { ++count; };
auto h = [v = std::move(v)]() { use(v); };

Rust

fn main() {
    let scale = 2.0f32;
    let f = |x: f32| x * scale;        // borrows `scale`
    let mut count = 0;
    let mut g = |_: i32| count += 1;   // mutably borrows `count`
    g(1);
    let v = vec![1, 2, 3];
    let h = move || v.len();           // takes ownership of `v`
    println!("{} {} {}", f(1.5), h(), count);
}

The big difference: you do not write a capture list. The compiler looks at what the body does with each variable and captures it the least powerful way that works: by shared reference if it only reads, by mutable reference if it mutates, by value if it moves the variable. The move keyword forces capture by value for everything, which you need when the closure outlives the current scope (threads, callbacks stored in structs).

Dangling captures, the classic [&] bug, are impossible: a closure that borrows a local is subject to the borrow checker like any other reference.

Fn, FnMut, FnOnce

Every closure has a unique, unnameable type (like a C++ lambda), which implements one or more of three traits depending on what it does with its captures:

TraitThe closure…Can be called
Fnonly reads its capturesAny number of times, even concurrently
FnMutmutates its capturesAny number of times, but needs &mut access
FnOnceconsumes (moves out) its capturesOnce

Functions that accept closures state which they need:

fn apply_twice(f: impl Fn(f32) -> f32, x: f32) -> f32 {
    f(f(x))
}

fn repeat(n: usize, mut f: impl FnMut(usize)) {
    for i in 0..n {
        f(i);
    }
}

fn on_shutdown(f: impl FnOnce() -> String) -> String {
    f()
}

fn main() {
    let gain = 1.5;
    println!("{}", apply_twice(|x| x * gain, 2.0));

    let mut log = Vec::new();
    repeat(3, |i| log.push(i * 10));
    println!("{log:?}");

    let name = String::from("renderer");
    println!("{}", on_shutdown(move || name + " stopped")); // consumes `name`
}

impl Fn(...) is a generic parameter, so each call is monomorphized and the closure is inlined, just like passing a lambda to a template. To store closures of different types in one place (a list of callbacks), box them: Vec<Box<dyn Fn(&Event)>>, the equivalent of std::function.

struct EventBus {
    listeners: Vec<Box<dyn Fn(&str)>>,
}

impl EventBus {
    fn subscribe(&mut self, f: impl Fn(&str) + 'static) {
        self.listeners.push(Box::new(f));
    }
    fn emit(&self, event: &str) {
        for l in &self.listeners {
            l(event);
        }
    }
}

fn main() {
    let mut bus = EventBus { listeners: Vec::new() };
    let prefix = String::from("[audio]");
    bus.subscribe(move |e| println!("{prefix} {e}"));
    bus.subscribe(|e| println!("[ui] {e}"));
    bus.emit("level_loaded");
}

Iterators

An iterator is any type implementing the Iterator trait, which has a single required method:

trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
    // ...plus about 75 provided methods: map, filter, sum, zip, ...
}
fn main() {}

That is the whole protocol: call next until it returns None. Compare with C++, where an iterator is a pair of positions (begin, end) that must come from the same container and stay valid.

Collections give you three iterators:

CallYieldsLike
v.iter() / for x in &v&Tfor (const auto& x : v)
v.iter_mut() / for x in &mut v&mut Tfor (auto& x : v)
v.into_iter() / for x in vT, consuming vmoving out of each element

A for loop is sugar for calling into_iter() and then next() until None.

Adapters and consumers

Adapters (map, filter, zip, enumerate, take, skip, chain, flat_map, rev, step_by, windows…) wrap an iterator in another iterator. They are lazy: nothing happens until a consumer (sum, count, collect, fold, for_each, min_by, any, position…) pulls values through.

#[derive(Debug, Clone, Copy)]
struct Light {
    position: [f32; 3],
    intensity: f32,
}

fn main() {
    let lights = vec![
        Light { position: [0.0, 5.0, 0.0], intensity: 10.0 },
        Light { position: [50.0, 5.0, 0.0], intensity: 3.0 },
        Light { position: [2.0, 1.0, 1.0], intensity: 0.0 },
        Light { position: [-4.0, 2.0, 3.0], intensity: 8.0 },
    ];
    let eye = [0.0f32, 1.0, 0.0];
    let dist2 = |p: [f32; 3]| (0..3).map(|i| (p[i] - eye[i]).powi(2)).sum::<f32>();

    // The 2 nearest lights that are switched on, with their original indices.
    let mut active: Vec<(usize, f32)> = lights
        .iter()
        .enumerate()
        .filter(|(_, l)| l.intensity > 0.0)
        .map(|(i, l)| (i, dist2(l.position)))
        .collect();
    active.sort_by(|a, b| a.1.total_cmp(&b.1));
    let nearest: Vec<usize> = active.iter().take(2).map(|&(i, _)| i).collect();
    println!("nearest lights: {nearest:?}");

    let total: f32 = lights.iter().map(|l| l.intensity).sum();
    let brightest = lights.iter().max_by(|a, b| a.intensity.total_cmp(&b.intensity));
    let any_off = lights.iter().any(|l| l.intensity == 0.0);
    println!("{total} {:?} {any_off}", brightest.map(|l| l.position));

    // Pairwise operations without index arithmetic:
    let path = [[0.0f32, 0.0], [3.0, 4.0], [3.0, 8.0]];
    let length: f32 = path
        .windows(2)
        .map(|w| ((w[1][0] - w[0][0]).powi(2) + (w[1][1] - w[0][1]).powi(2)).sqrt())
        .sum();
    println!("path length {length}");
}

collect() builds any collection that implements FromIterator: Vec, HashMap (from pairs), String (from chars), even Result<Vec<T>, E> (from an iterator of Results, stopping at the first error).

Zero cost: check the assembly

The claim "iterators are as fast as loops" is checkable. Open both of these on the Playground (link under the example), set Release, and choose Show Assembly from the menu next to Run:

pub fn sum_of_squares_loop(xs: &[i32]) -> i32 {
    let mut total = 0;
    for i in 0..xs.len() {
        total += xs[i] * xs[i];     // bounds check here...
    }
    total
}

pub fn sum_of_squares_iter(xs: &[i32]) -> i32 {
    xs.iter().map(|x| x * x).sum()  // ...and none here
}
fn main() {
    let v: Vec<i32> = (1..=10).collect();
    assert_eq!(sum_of_squares_loop(&v), sum_of_squares_iter(&v));
    println!("{}", sum_of_squares_iter(&v));
}

Both produce the same vectorized loop. In the indexed version, the compiler proves i < xs.len() from the loop bounds and removes the bounds check; in the iterator version there was never a check to remove. When the compiler cannot prove an index is in range (say, xs[i + offset]), the indexed version keeps its check and the iterator version (xs.iter().skip(offset), zip, chunks_exact) is faster.

Debug builds

In a debug build (opt-level = 0), iterator chains are not inlined and are much slower than raw loops, often by 10 to 50 times. This is the main reason to set opt-level = 1 for your own code in the dev profile, as shown in the Cargo chapter.

Writing your own iterator

Implement next, and every adapter is available for free:

/// Iterates the cells of a w x h grid in Morton (Z-order) curve order.
struct Morton {
    i: u32,
    w: u32,
    h: u32,
}

fn deinterleave(mut x: u32) -> u32 {
    x &= 0x5555_5555;
    x = (x | (x >> 1)) & 0x3333_3333;
    x = (x | (x >> 2)) & 0x0f0f_0f0f;
    x = (x | (x >> 4)) & 0x00ff_00ff;
    (x | (x >> 8)) & 0x0000_ffff
}

impl Iterator for Morton {
    type Item = (u32, u32);
    fn next(&mut self) -> Option<(u32, u32)> {
        let side = self.w.max(self.h).next_power_of_two();
        while self.i < side * side {
            let (x, y) = (deinterleave(self.i), deinterleave(self.i >> 1));
            self.i += 1;
            if x < self.w && y < self.h {
                return Some((x, y));
            }
        }
        None
    }
}

fn main() {
    let cells: Vec<_> = Morton { i: 0, w: 4, h: 2 }.collect();
    println!("{cells:?}");
    let diagonal = Morton { i: 0, w: 8, h: 8 }.filter(|(x, y)| x == y).count();
    println!("{diagonal}");
}

For simple cases, std::iter::from_fn(|| ...) and std::iter::successors build an iterator from a closure without defining a type.

Summary

C++Rust
Lambda with capture listClosure; captures inferred, move for by-value
std::function<R(A)>Box<dyn Fn(A) -> R>
Template parameter for a callableimpl Fn(A) -> R / F: FnMut(A) -> R
Iterator pair begin/endOne iterator object with next()
<algorithm>, rangesIterator adapters and consumers
std::transform + back_inserter.map(...).collect()
std::accumulate.fold(...) / .sum()

Exercises

  1. Rewrite the "nearest lights" example with a single fold (no sorting) to find the one nearest active light.
  2. Write a function that takes impl FnMut() -> f32 (a random generator) and returns a Vec<[f32; 2]> of n points in the unit circle using rejection sampling. Use std::iter::repeat_with and filter.
  3. In the Playground, compare the assembly of sum_of_squares_loop with a version that indexes xs[i + 1] for i in 0..xs.len() - 1. Find the bounds check, then remove it with windows(2).

Smart pointers and interior mutability

You know std::unique_ptr and std::shared_ptr. Rust has direct equivalents, Box and Rc/Arc, and they behave the way you expect, with two twists: ownership rules apply to them like to everything else, so many of their C++ footguns disappear, and shared ownership combines with Rust's "shared XOR mutable" rule in a way that needs a new tool, interior mutability.

This chapter covers:

  • Box<T> and when you actually need it,
  • Rc<T> and Arc<T>, and why there are two,
  • Weak<T> and reference cycles,
  • Cell and RefCell: mutation through a shared reference,
  • the common combinations, and when to avoid them.

Box<T>: one owner, on the heap

Box<T> is a pointer to a heap allocation that it owns, exactly like std::unique_ptr<T>. It is one pointer wide, never null, and frees its contents when dropped.

#[derive(Debug)]
enum Node {
    Leaf(u32),
    Branch(Box<Node>, Box<Node>),   // recursion needs indirection
}

fn sum(n: &Node) -> u32 {
    match n {
        Node::Leaf(v) => *v,
        Node::Branch(l, r) => sum(l) + sum(r),
    }
}

fn main() {
    let tree = Node::Branch(Box::new(Node::Leaf(1)), Box::new(Node::Branch(
        Box::new(Node::Leaf(2)),
        Box::new(Node::Leaf(3)),
    )));
    println!("{}", sum(&tree));

    let big = Box::new([0u8; 1 << 16]);   // 64 KiB on the heap, not the stack
    println!("{}", big.len());
}

You need Box less often than unique_ptr, because Rust values are moved cheaply without heap allocation, and Vec, String and HashMap already manage their heap memory. Use Box for:

  • recursive types, as above (a type cannot contain itself directly),
  • trait objects: Box<dyn Trait>,
  • large values you want to move around without copying many bytes,
  • stable addresses for data handed to C code.

Rc<T> and Arc<T>: shared ownership

Rc<T> ("reference counted") is shared_ptr<T>: many owners, and the value is dropped when the last one goes away. Cloning an Rc increments the count; it does not clone the value.

use std::rc::Rc;

#[derive(Debug)]
struct Mesh {
    name: String,
    vertex_count: u32,
}

struct Instance {
    mesh: Rc<Mesh>,
    transform: [f32; 3],
}

fn main() {
    let rock = Rc::new(Mesh { name: "rock".into(), vertex_count: 1200 });
    let instances: Vec<Instance> = (0..3)
        .map(|i| Instance { mesh: Rc::clone(&rock), transform: [i as f32, 0.0, 0.0] })
        .collect();
    println!("{} owners", Rc::strong_count(&rock));   // 4
    for inst in &instances {
        println!("{} at {:?} ({} verts)", inst.mesh.name, inst.transform, inst.mesh.vertex_count);
    }
    drop(instances);
    println!("{} owner", Rc::strong_count(&rock));    // 1
}

Why two types? shared_ptr always uses atomic increments, because it cannot know whether it will be shared across threads. Rust can know: Rc uses plain, non-atomic counts and the compiler forbids sending it to another thread (it does not implement Send; see Concurrency). Arc ("atomically reference counted") uses atomic counts and can be shared between threads. You get the cheap version by default and the compiler tells you when you need the expensive one.

Two more differences from shared_ptr:

  • The value inside an Rc is immutable through the Rc. Rc<T> gives you &T, never &mut T, because other owners might be reading it. Mutation needs interior mutability, below.
  • Rc::new allocates the counts and the value together, like std::make_shared. There is no separate control block.

Weak<T> and cycles

Reference counting cannot free cycles: if A owns B and B owns A, both counts stay above zero forever. As with weak_ptr, the fix is a non-owning Weak pointer for back-edges such as child-to-parent links. upgrade() returns an Option<Rc<T>>, which is None once the value is gone:

use std::cell::RefCell;
use std::rc::{Rc, Weak};

struct SceneNode {
    name: String,
    parent: RefCell<Weak<SceneNode>>,        // back-edge: does not keep the parent alive
    children: RefCell<Vec<Rc<SceneNode>>>,   // owning edges
}

fn node(name: &str) -> Rc<SceneNode> {
    Rc::new(SceneNode {
        name: name.into(),
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(Vec::new()),
    })
}

fn add_child(parent: &Rc<SceneNode>, child: Rc<SceneNode>) {
    *child.parent.borrow_mut() = Rc::downgrade(parent);
    parent.children.borrow_mut().push(child);
}

fn main() {
    let root = node("root");
    let arm = node("arm");
    add_child(&root, Rc::clone(&arm));
    add_child(&arm, node("hand"));

    let parent_name = arm.parent.borrow().upgrade().map(|p| p.name.clone());
    println!("arm's parent: {parent_name:?}");
    println!("root strong={} weak={}", Rc::strong_count(&root), Rc::weak_count(&root));
    drop(root);
    println!("after dropping root: {:?}", arm.parent.borrow().upgrade().map(|p| p.name.clone()));
}

This works, but look at how much ceremony a parent/child tree takes: Rc, Weak, RefCell, borrow_mut, upgrade. That is a strong hint. In Rust, graphs of objects that point at each other are usually better stored in an arena with indices or handles; see Handles and arenas. A scene graph becomes a Vec<Node> where parent: Option<NodeId>.

Interior mutability: Cell and RefCell

The borrow rules say: many &T or one &mut T. Sometimes you need to mutate something that is reachable only through a shared reference: a cache inside an otherwise immutable object, a counter in an Rc, the children list above. C++ has mutable for the first case and nothing in particular for the rest.

Rust's answer is types that allow mutation through &self while keeping the guarantees, by checking in a different way:

TypeHow it stays safeCostC++ analogue
Cell<T>Never hands out references: only get (copy out) and set (replace)ZeroA mutable member of trivial type
RefCell<T>Tracks borrows at run time; a conflicting borrow panicsA counter and a check per borrowmutable + a debug assertion
Mutex<T>, RwLock<T>Locking; thread-safeA lockstd::mutex next to the data
AtomicsHardware atomics; thread-safeAtomic opsstd::atomic<T>
use std::cell::{Cell, RefCell};

struct Material {
    name: String,
    shader_compiles: Cell<u32>,                // statistics, mutated through &self
    cached_hash: RefCell<Option<u64>>,          // lazily computed
}

impl Material {
    fn hash(&self) -> u64 {                     // &self, not &mut self
        if let Some(h) = *self.cached_hash.borrow() {
            return h;
        }
        let h = self.name.bytes().fold(14695981039346656037u64, |h, b| {
            (h ^ b as u64).wrapping_mul(1099511628211)
        });
        *self.cached_hash.borrow_mut() = Some(h);
        self.shader_compiles.set(self.shader_compiles.get() + 1);
        h
    }
}

fn main() {
    let m = Material { name: "brick".into(), shader_compiles: Cell::new(0), cached_hash: RefCell::new(None) };
    let a = m.hash();
    let b = m.hash();
    println!("{a:x} {b:x} computed {} time(s)", m.shader_compiles.get());

    // RefCell enforces the rules at run time:
    let list = RefCell::new(vec![1, 2, 3]);
    let reader = list.borrow();
    // let writer = list.borrow_mut();   // would panic: already borrowed
    println!("{:?} {:?}", reader, list.try_borrow_mut().is_err());
}

RefCell moves the borrow check from compile time to run time. That is sometimes necessary, but every borrow_mut() is a potential panic that the compiler can no longer rule out. Keep RefCell borrows short, and prefer a design where ownership is clear enough that you do not need it.

Common combinations

TypeMeaning
Box<T>Single owner, heap
Rc<T>Shared ownership, read-only, one thread
Rc<RefCell<T>>Shared ownership, mutable, one thread, run-time borrow checks
Arc<T>Shared ownership, read-only, any thread
Arc<Mutex<T>> / Arc<RwLock<T>>Shared ownership, mutable, any thread
Weak<T>Non-owning back-reference
C++ habit to unlearn

When the borrow checker rejects a design ported from C++, Rc<RefCell<T>> everywhere makes the errors go away. It also gives you a program full of reference counts and run-time borrow panics, which is the C++ design with extra overhead. It is fine for a few genuinely shared objects. If it is your default, the data model needs rethinking: one owner (often a Vec or an arena) and handles everywhere else.

Summary

C++Rust
std::unique_ptr<T>Box<T>
std::make_unique<T>(...)Box::new(...)
std::shared_ptr<T> (atomic counts)Rc<T> (single thread) or Arc<T> (atomic)
std::make_shared<T>(...)Rc::new(...) / Arc::new(...)
std::weak_ptr<T>, lock()Weak<T>, upgrade()
mutable memberCell<T> / RefCell<T>
shared_ptr<T> with std::mutex memberArc<Mutex<T>>

Exercises

  1. In the Rc<Mesh> example, try to change inst.mesh.vertex_count through an instance. Read the error, then make it work with Cell<u32>.
  2. Rewrite the scene node tree without Rc: store nodes in a Vec<Node> with parent: Option<usize> and children: Vec<usize>. Write a function that returns the path from a node to the root as names.
  3. Write a program that panics with already borrowed: BorrowMutError using RefCell, then fix it by shortening the first borrow.

Modules and project organization

C++ organizes code with three unrelated mechanisms: files and #include for compilation, namespaces for names, and access specifiers for visibility (plus static libraries, static linkage and anonymous namespaces for "private to this file"). C++20 modules try to unify them, slowly. Rust has one system: modules give you files, namespaces and visibility at once, and crates group modules into units of compilation.

This chapter covers:

  • declaring modules and mapping them to files,
  • pub and the visibility levels,
  • use paths and re-exports,
  • laying out a larger project,
  • how crate boundaries affect compile times.

Modules are namespaces with visibility

mod math {
    pub struct Vec2 {
        pub x: f32,
        pub y: f32,
    }

    pub fn length(v: &Vec2) -> f32 {
        sqrt_approx(v.x * v.x + v.y * v.y)
    }

    // Private: visible only inside `math` and its children.
    fn sqrt_approx(x: f32) -> f32 {
        x.sqrt()
    }

    pub mod consts {
        pub const TAU: f32 = std::f32::consts::TAU;
    }
}

use math::{Vec2, consts::TAU};

fn main() {
    let v = Vec2 { x: 3.0, y: 4.0 };
    println!("{} {}", math::length(&v), TAU);
    // math::sqrt_approx(2.0);   // error[E0603]: function `sqrt_approx` is private
}

Everything is private by default: to its module and the module's descendants. pub makes an item visible to whoever can see the module. Struct fields have their own visibility, so a struct can be public while its fields stay private, which is how types enforce invariants (only the module's own functions can construct or modify them).

VisibilityVisible to
(nothing)This module and its children
pub(super)The parent module
pub(crate)The whole crate, but not other crates
pubEveryone who can reach the module

pub(crate) covers what C++ projects do with "internal" headers and detail namespaces, with the compiler enforcing it.

Modules and files

mod name { ... } defines a module inline. mod name; (with a semicolon) tells the compiler to load it from a file:

src/
├── main.rs            // mod render; mod world;
├── render.rs          // mod pipeline; mod texture;   (render's own code here)
├── render/
│   ├── pipeline.rs
│   └── texture.rs
└── world.rs
// src/main.rs
mod render;            // loads src/render.rs
mod world;             // loads src/world.rs

fn main() {
    let mut r = render::Renderer::new();
    let w = world::World::default();
    r.draw(&w);
}
// src/render.rs
mod pipeline;          // loads src/render/pipeline.rs
mod texture;           // loads src/render/texture.rs

pub use texture::Texture;   // re-export: users write render::Texture

pub struct Renderer { /* ... */ }

The module tree is declared explicitly from the crate root (main.rs or lib.rs), and files that are not declared are not compiled. There is no build script listing sources and no include path. (An older layout, render/mod.rs instead of render.rs, also works and you will see it in existing code.)

use paths

use brings names into scope, like using declarations. Paths start from:

Path startMeaning
crate::The root of the current crate
self::The current module
super::The parent module
some_crate::An external crate (a dependency)
std::, core::The standard library
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use crate::render::{Renderer, Texture};
use super::world::World as GameWorld;    // rename on import
use glam::*;                             // glob import: use sparingly

Re-exporting with pub use lets a crate present a clean public API that does not mirror its internal file layout. Large crates typically have a prelude module that re-exports the most common items, so users can write use bevy::prelude::*;.

What you no longer need
  • Include guards and #pragma once: modules are declared once in the tree.
  • Forward declarations: items can be used before or after their definition, in any module.
  • The ODR: every item has one definition, in one module.
  • Header/source pairs: a module's public items are its interface.
  • Pimpl for compile firewalls: private fields of a struct are already hidden from other crates' code. (Changing them still triggers recompilation of dependents; see below.)

Organizing a larger project

A pattern that scales well:

my-engine/                  (a workspace, see the Cargo chapter)
├── Cargo.toml
├── crates/
│   ├── engine-core/        math, handles, logging. Depends on almost nothing.
│   ├── engine-ecs/         entities, components, scheduling
│   ├── engine-render/      GPU abstraction; depends on core
│   ├── engine-assets/      loading, caching, hot reload
│   └── engine/             the public facade: re-exports the others
└── games/
    └── demo/               a binary crate using `engine`

Inside each crate:

  • lib.rs declares modules and re-exports the public API. Keep it short.
  • One module per concept (texture.rs, pipeline.rs), not per type. Rust files are routinely several hundred lines.
  • Put unit tests at the bottom of each file in a #[cfg(test)] mod tests (Testing chapter).
  • Keep pub surfaces small and use pub(crate) for helpers shared inside the crate.

Compile times and crate boundaries

The crate is the unit of compilation:

  • Within a crate, the compiler splits work into "codegen units" for parallel LLVM optimization, but type checking and borrow checking run over the whole crate. A change anywhere in a crate recompiles that crate (incrementally, reusing what it can).
  • Across crates, a change to crate A rebuilds every crate that depends on A. Crates that do not depend on each other build in parallel.

So the guidance mirrors what you would do with C++ libraries, with the emphasis shifted:

  1. Split along stable interfaces. A math crate that rarely changes can be depended on by everything at no cost.
  2. Keep the dependency graph wide, not deep: render, audio and physics depending only on core build in parallel.
  3. Generic code is compiled in the crate that uses it, like templates. Heavy generic code in a low-level crate makes every dependent crate slower to build. Where possible, have generic functions do minimal work and call a non-generic inner function.
  4. Measure with cargo build --timings, which produces an HTML report of which crates took how long and what ran in parallel.

Summary

C++Rust
namespacemod
#include + header filemod name; declares a file as a module; use imports names
using std::vector;use std::vec::Vec;
public / private (classes)pub / private by default (modules and fields)
Anonymous namespace, static functionsPrivate items
detail namespace, internal headerspub(crate)
Static libraryLibrary crate
Umbrella headerpub use re-exports, prelude module

Exercises

  1. Turn the inline math module above into a file src/math.rs with a submodule src/math/consts.rs. Which mod lines do you need, and where?
  2. Make Vec2's fields private and add Vec2::new and getters. What can code outside math no longer do?
  3. In a workspace with two crates, mark a function pub(crate) and try to call it from the other crate. Read the error.

Threads, locks and Send/Sync

Rust's threads are OS threads, its atomics follow the C++11 memory model, and its mutex is a thin wrapper over the platform's lock. Nothing here is new to you. What is new is that data races are compile errors. The same ownership and borrowing rules that prevent use-after-free also prevent two threads from touching the same data without synchronization, and two marker traits, Send and Sync, extend the rules across threads.

This chapter covers:

  • spawning threads, and scoped threads that can borrow,
  • Send and Sync,
  • Mutex<T>: a lock that owns its data,
  • RwLock, Condvar, atomics and memory ordering,
  • channels,
  • data parallelism with rayon, the job system you do not have to write.

Spawning threads

use std::thread;

fn main() {
    let handles: Vec<_> = (0..4)
        .map(|id| {
            thread::spawn(move || {
                let sum: u64 = (id * 1000..(id + 1) * 1000).sum();
                sum                              // the thread's return value
            })
        })
        .collect();

    let total: u64 = handles.into_iter().map(|h| h.join().unwrap()).sum();
    println!("{total}");
}

thread::spawn takes a closure and returns a JoinHandle, like std::thread returning a future-like handle. The closure must be 'static (it may outlive the caller), so it must own what it uses: hence move. A JoinHandle that is dropped without join detaches the thread rather than calling std::terminate like an unjoined std::thread.

Scoped threads

Often you want threads that work on data owned by the caller and finish before the caller returns, the fork-join pattern. thread::scope guarantees all threads spawned inside it are joined at the end of the scope, so they are allowed to borrow local data:

use std::thread;

fn main() {
    let mut pixels = vec![0u32; 1920 * 1080];
    let width = 1920;

    thread::scope(|s| {
        // Split the image into 8 horizontal bands, one thread each.
        for (band, rows) in pixels.chunks_mut(width * 1080 / 8).enumerate() {
            s.spawn(move || {
                for (i, p) in rows.iter_mut().enumerate() {
                    *p = (band as u32) << 24 | (i % width) as u32;
                }
            });
        }
    }); // all threads joined here

    println!("{:#x} {:#x}", pixels[0], pixels[pixels.len() - 1]);
}

Each thread gets a &mut to a disjoint band from chunks_mut, so the borrow checker can see there is no overlap. Try giving two threads the same band and the program will not compile.

Send and Sync

Two marker traits, implemented automatically by the compiler, describe what may cross thread boundaries:

  • Send: a value of this type can be moved to another thread.
  • Sync: a value of this type can be shared between threads by reference (T is Sync if &T is Send).

Almost everything is both: integers, String, Vec<T> (if T is), your own structs made of such fields. The exceptions are the types whose correctness depends on not being shared:

TypeSendSyncWhy
Rc<T>nonoNon-atomic reference count
Arc<T>yes*yes*Atomic count (*if T is Send + Sync)
Cell<T>, RefCell<T>yesnoUnsynchronized interior mutability
Mutex<T>yes*yes*Locking makes shared access safe (*if T: Send)
Raw pointers *const T, *mut TnonoThe compiler cannot know; you assert it with unsafe impl

thread::spawn requires its closure to be Send. So this fails to compile, where the C++ equivalent with shared_ptr and a non-atomic member races at run time:

use std::rc::Rc;
use std::thread;

fn main() {
    let config = Rc::new(String::from("high"));
    let c = Rc::clone(&config);
    thread::spawn(move || {
        println!("{c}");   // error[E0277]: `Rc<String>` cannot be sent between threads safely
    });
}

Replace Rc with Arc and it compiles.

Mutex<T>: the lock owns the data

In C++, a mutex sits next to the data it protects, and a comment says which fields it guards. Nothing stops code from touching the data without the lock.

C++

struct Stats {
    std::mutex m;          // protects frames, dropped
    uint64_t frames = 0;
    uint64_t dropped = 0;
};

void on_frame(Stats& s, bool late) {
    std::lock_guard lock(s.m);
    ++s.frames;
    if (late) ++s.dropped;
}
// Elsewhere: s.frames++;  // compiles, races

Rust

use std::sync::Mutex;

struct Counts {
    frames: u64,
    dropped: u64,
}

struct Stats {
    counts: Mutex<Counts>,   // the only way in is lock()
}

fn on_frame(s: &Stats, late: bool) {
    let mut c = s.counts.lock().unwrap();
    c.frames += 1;
    if late {
        c.dropped += 1;
    }
}   // guard dropped: unlocked
fn main() {
    let s = Stats { counts: Mutex::new(Counts { frames: 0, dropped: 0 }) };
    on_frame(&s, true);
    println!("{}", s.counts.lock().unwrap().dropped);
}

Mutex<T> contains the T. The only way to reach it is lock(), which returns a guard that dereferences to &mut T and unlocks when dropped, like std::lock_guard fused with the data. The guard borrows the mutex, so you cannot keep a reference to the data after unlocking: that would be a borrow outliving its owner, and it does not compile.

lock() returns a Result because of poisoning: if a thread panicked while holding the lock, the data may be half-updated, and later lockers get an error they can inspect. unwrap() (propagate the panic) is the usual response.

Sharing a mutex among threads uses Arc:

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let log = Arc::new(Mutex::new(Vec::new()));
    let workers: Vec<_> = (0..4)
        .map(|id| {
            let log = Arc::clone(&log);
            thread::spawn(move || {
                for job in 0..3 {
                    log.lock().unwrap().push(format!("worker {id} job {job}"));
                }
            })
        })
        .collect();
    for w in workers {
        w.join().unwrap();
    }
    println!("{} entries", log.lock().unwrap().len());
}

The borrow checker prevents data races. It does not prevent deadlocks or logic races (check-then-act across two separate locks). Lock ordering is still your job.

Other primitives

C++RustNotes
std::shared_mutexRwLock<T>read() and write() guards
std::condition_variableCondvarUsed with a MutexGuard
std::call_once, function-local staticOnceLock<T>, LazyLock<T>Thread-safe lazy initialization
std::atomic<int> etc.AtomicI32, AtomicU64, AtomicBool, AtomicPtr<T>Methods take an Ordering
std::memory_order_relaxed … seq_cstOrdering::Relaxed, Acquire, Release, AcqRel, SeqCstThe same C++11 model (minus consume)
std::barrier, std::latchBarrier
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::LazyLock;
use std::thread;

static NEXT_ENTITY: AtomicU32 = AtomicU32::new(1);       // no Mutex needed
static SHADER_DIR: LazyLock<String> = LazyLock::new(|| "assets/shaders".to_string());

fn new_entity() -> u32 {
    NEXT_ENTITY.fetch_add(1, Ordering::Relaxed)            // unique IDs: relaxed is enough
}

fn main() {
    // Publish a result from one thread to another: release/acquire, as in C++.
    let result = AtomicU64::new(0);
    let ready = AtomicBool::new(false);
    thread::scope(|s| {
        s.spawn(|| {
            result.store(42, Ordering::Relaxed);
            ready.store(true, Ordering::Release);          // everything before is visible...
        });
        while !ready.load(Ordering::Acquire) {             // ...to whoever sees `true` here
            std::hint::spin_loop();
        }
        println!("result {}", result.load(Ordering::Relaxed));
    });

    let ids: Vec<u32> = (0..3).map(|_| new_entity()).collect();
    println!("{ids:?} {}", *SHADER_DIR);
}

Atomics and their orderings behave exactly as in C++. If you know the C++ memory model, you know Rust's. Mara Bos's Rust Atomics and Locks is the in-depth reference.

Channels

Message passing is often simpler than shared state. std::sync::mpsc is a multi-producer, single-consumer queue:

use std::sync::mpsc;
use std::thread;

enum LoadResult {
    Mesh { name: String, triangles: u32 },
    Failed(String),
}

fn main() {
    let (tx, rx) = mpsc::channel();
    for name in ["rock", "tree", "missing"] {
        let tx = tx.clone();
        thread::spawn(move || {
            let msg = if name == "missing" {
                LoadResult::Failed(name.into())
            } else {
                LoadResult::Mesh { name: name.into(), triangles: name.len() as u32 * 1000 }
            };
            tx.send(msg).unwrap();   // ownership of msg moves to the receiver
        });
    }
    drop(tx); // close our copy so the loop below ends when all senders are done

    for msg in rx {
        match msg {
            LoadResult::Mesh { name, triangles } => println!("loaded {name}: {triangles} tris"),
            LoadResult::Failed(name) => println!("failed: {name}"),
        }
    }
}

Sending moves the value: the sender can no longer touch it, so no locking is needed for the payload. For multi-consumer queues, select, and better performance, the crossbeam-channel crate is the common choice.

Data parallelism with rayon

Most engine parallelism is "do this for every element, in parallel": cull objects, skin meshes, update particles. The rayon crate turns an iterator chain into a parallel one by changing iter() to par_iter(), running it on a work-stealing thread pool:

use rayon::prelude::*;

fn update_particles(ps: &mut [Particle], dt: f32) {
    ps.par_iter_mut().for_each(|p| {        // split across all cores
        p.velocity += GRAVITY * dt;
        p.position += p.velocity * dt;
    });
}

fn visible(objects: &[Object], frustum: &Frustum) -> Vec<u32> {
    objects
        .par_iter()
        .filter(|o| frustum.intersects(&o.bounds))
        .map(|o| o.id)
        .collect()                           // order is preserved
}

// Fork-join: run two independent jobs in parallel.
let (shadows, gbuffer) = rayon::join(|| record_shadow_pass(&scene), || record_gbuffer(&scene));

The borrow rules make this safe: par_iter_mut hands each worker a disjoint &mut element, and a closure that tried to write to shared state without synchronization would not compile. This is the job system a C++ engine spends months building and debugging, as a library.

Summary

C++Rust
std::threadstd::thread::spawn (requires 'static + Send)
Fork-join over local datastd::thread::scope
Data race (UB, found by TSan)Compile error
std::mutex beside the dataMutex<T> containing the data
std::lock_guardMutexGuard, returned by lock()
shared_ptr<T> across threadsArc<T>
std::atomic<T>AtomicXxx with explicit Ordering
Hand-written job system / TBBrayon

Exercises

  1. Write a scoped-thread version of a parallel sum over a Vec<f32>, splitting it into one chunk per available core (std::thread::available_parallelism).
  2. Make the Stats example count per-thread with AtomicU64s instead of a mutex. Which Ordering is enough, and why?
  3. Build a tiny job queue: a Mutex<VecDeque<Box<dyn FnOnce() + Send>>> with a Condvar, and four worker threads that run jobs until a shutdown flag is set.

Memory layout and performance

Rust compiles through LLVM, the same back end as Clang, so for equivalent code you get equivalent machine code. Performance work in Rust is the performance work you already do: control the layout, keep data contiguous, avoid allocations in the hot path, measure. This chapter shows the Rust spelling of each technique, and the few places where Rust's defaults differ from C++.

This chapter covers:

  • inspecting size and alignment, and controlling layout,
  • array-of-structs versus struct-of-arrays,
  • where the hidden costs are: bounds checks, overflow checks, allocations, dynamic dispatch,
  • allocators: global, arena and bump,
  • profiling and reading assembly.

Size, alignment and layout

std::mem::size_of::<T>() and align_of::<T>() are sizeof and alignof. std::mem::offset_of!(Type, field) is offsetof. The layout attributes were introduced in Values, types and layout; the rules again in one place:

AttributeEffect
(default)Compiler may reorder fields to reduce padding; layout unspecified
#[repr(C)]Declaration order, C padding rules; stable and FFI-safe
#[repr(align(N))]Minimum alignment N (cache-line alignment, SIMD)
#[repr(transparent)]Same layout and ABI as the single non-zero-sized field
#[repr(u8)] etc. on enumsExplicit discriminant type
#[repr(packed)]No padding; references to fields are not allowed
use std::mem::{align_of, offset_of, size_of};

#[repr(C)]
struct InstanceData {
    model: [[f32; 4]; 4], // 64 bytes
    color: [f32; 4],      // 16
    material: u32,        // 4
    flags: u32,           // 4  -> 88 bytes; std140 would need padding to 96
}

#[repr(C, align(16))]
struct Aligned([f32; 3]);

fn main() {
    println!("InstanceData: {} bytes, align {}", size_of::<InstanceData>(), align_of::<InstanceData>());
    println!("material at offset {}", offset_of!(InstanceData, material));
    println!("Aligned: {} bytes", size_of::<Aligned>());   // 16: padded to its alignment
}

Rust's default of reordering fields means a struct written in "logical" order is already compact. You only need to think about order for #[repr(C)] structs, which are the ones shared with GPUs, files and C.

AoS versus SoA

Everything you know about data-oriented design applies unchanged. An array of structs:

#[derive(Clone, Copy, Default)]
struct Particle {
    position: [f32; 3],
    velocity: [f32; 3],
    color: [u8; 4],
    age: f32,
}
fn main() {}

wastes bandwidth when the hot loop touches only position and velocity. A struct of arrays keeps each field contiguous:

#[derive(Default)]
struct Particles {
    px: Vec<f32>, py: Vec<f32>, pz: Vec<f32>,
    vx: Vec<f32>, vy: Vec<f32>, vz: Vec<f32>,
    age: Vec<f32>,
}

impl Particles {
    fn integrate(&mut self, dt: f32) {
        let n = self.px.len();
        // Re-slicing to the same length lets the compiler drop bounds checks.
        let (px, vx) = (&mut self.px[..n], &self.vx[..n]);
        for i in 0..n {
            px[i] += vx[i] * dt;
        }
        // Or zip, which never had checks:
        for (py, vy) in self.py.iter_mut().zip(&self.vy) {
            *py += vy * dt;
        }
        for (pz, vz) in self.pz.iter_mut().zip(&self.vz) {
            *pz += vz * dt;
        }
        for a in &mut self.age {
            *a += dt;
        }
    }
}

fn main() {
    let mut p = Particles::default();
    for i in 0..8 {
        p.px.push(0.0); p.py.push(0.0); p.pz.push(0.0);
        p.vx.push(i as f32); p.vy.push(1.0); p.vz.push(0.0);
        p.age.push(0.0);
    }
    p.integrate(0.5);
    println!("{:?}", p.px);
}

These loops auto-vectorize. The borrow checker helps here in a way C++ does not: because self.px and self.vx are distinct fields borrowed as &mut and &, the compiler knows they do not alias, which is exactly what the vectorizer needs.

The hidden costs, and how to see them

Rust adds very few costs C++ does not have, and each is visible in the source:

CostWhenHow to avoid
Bounds checksslice[i] where the compiler cannot prove i in rangeIterators, zip, chunks_exact, re-slicing to a known length, assert!(i < len) before a loop; get_unchecked (unsafe) as a last resort
Overflow checksDebug builds only (by default)Use wrapping_* where wrapping is intended
Drop flagsValues moved on only some pathsRarely matters
Dynamic dispatchdyn Trait callsGenerics; enums
AllocationBox::new, Vec::push beyond capacity, String building, format!, collect()Reuse buffers (clear() keeps capacity), with_capacity, arenas
Reference countingRc/Arc::clonePass &T instead of cloning the Arc
RefCell borrow checksEvery borrow() / borrow_mut()Restructure ownership

A bounds check is a compare and a well-predicted branch. In most code it does not show up in profiles. Where it does, it usually also blocks vectorization, and the fixes above remove it without unsafe.

C++ habit to unlearn

Do not reach for unsafe { get_unchecked() } because "bounds checks are slow". Look at the assembly first. In practice an iterator or a single assert!(idx.len() == data.len()) before the loop lets LLVM remove the checks, and you keep the safety net.

Allocation

Rust has no new operator and no hidden allocations in the language: every heap allocation comes from a library type (Box, Vec, String, Rc, HashMap…). The standard library's allocator is the system malloc by default. You can replace it for the whole program, like replacing operator new:

// Use mimalloc for every allocation in the program.
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;

Or implement GlobalAlloc yourself, for instance to count allocations per frame:

use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};

struct Counting;
static ALLOCS: AtomicUsize = AtomicUsize::new(0);

unsafe impl GlobalAlloc for Counting {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        ALLOCS.fetch_add(1, Ordering::Relaxed);
        unsafe { System.alloc(layout) }
    }
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        unsafe { System.dealloc(ptr, layout) }
    }
}

#[global_allocator]
static GLOBAL: Counting = Counting;

fn frame(scratch: &mut Vec<u32>) {
    scratch.clear();                 // keeps capacity: no allocation after warm-up
    scratch.extend(0..1000);
}

fn main() {
    let mut scratch = Vec::new();
    for f in 0..3 {
        let before = ALLOCS.load(Ordering::Relaxed);
        frame(&mut scratch);
        println!("frame {f}: {} allocations", ALLOCS.load(Ordering::Relaxed) - before);
    }
}

Per-collection custom allocators (like std::vector<T, Alloc>) are still unstable in the standard library. In practice engines use:

  • Reusable buffers: keep a Vec across frames and clear() it.
  • Bump allocators (bumpalo) for per-frame scratch data, with the borrow checker ensuring nothing outlives the reset (Handles and arenas).
  • Pools and slot maps for objects with individual lifetimes.

Inlining and codegen

  • Small functions are inlined within a crate automatically. Across crates, non-generic functions are inlined only with LTO or if marked #[inline]. Generic functions are always available for inlining, like templates.
  • #[inline(always)] and #[inline(never)] are hints with the usual caveats. #[cold] marks unlikely paths, like [[unlikely]].
  • opt-level = 3, lto = "fat" or "thin", codegen-units = 1 and -C target-cpu=native in .cargo/config.toml are the main build knobs (Cargo).
  • panic = "abort" removes unwinding tables and landing pads.
  • Profile-guided optimization works via -C profile-generate / -C profile-use (or the cargo-pgo helper).

Profiling and reading assembly

Your profilers work unchanged; make sure symbols are present in optimized builds:

[profile.release]
debug = "line-tables-only"   # or `true` for full debug info
  • Sampling profilers: perf, VTune, Superluminal, Instruments, Windows Performance Analyzer. cargo flamegraph wraps perf/dtrace and produces an SVG flame graph.
  • Instrumented: Tracy (via tracy-client or the tracing-tracy layer) and puffin for in-game frame profilers.
  • Assembly: cargo asm (the cargo-show-asm tool) prints the assembly of a single function. The Playground and Compiler Explorer (godbolt.org) show assembly in the browser; every example in this book has a link to open it in the Playground.
  • Benchmarks: criterion for statistically sound microbenchmarks (Testing).

Summary

C++Rust
sizeof, alignof, offsetofsize_of, align_of, offset_of!
Declaration-order layoutReordered by default; #[repr(C)] for declaration order
alignas#[repr(align(N))]
__restrictImplied by &mut
Replace operator new#[global_allocator]
std::pmr, allocator template parametersMostly crates: bumpalo, slot maps; allocator API unstable
[[likely]] / [[unlikely]]#[cold] on functions
-fprofile-generate-C profile-generate

Exercises

  1. Write the particle update in AoS form (Vec<Particle>) and SoA form, and compare their assembly in the Playground. Which one vectorizes?
  2. Use the counting allocator to find every allocation in a small program that builds strings with format! in a loop. Remove them by reusing a String with write! (from std::fmt::Write).
  3. Write a loop that sums data[idx[i]] for an index array. Look for the bounds check in the assembly. Can you remove it safely?

Unsafe Rust

Everything so far has been safe Rust: code in which the compiler guarantees no undefined behavior. Some code cannot be checked by the compiler: calling C functions, talking to hardware, implementing a new collection on raw memory, using SIMD intrinsics. For those, Rust has the unsafe keyword. As a C++ programmer you will find unsafe Rust familiar, since it is roughly what you write every day, but the rules are stricter than you might expect, and the way it is used is very different.

This chapter covers:

  • what unsafe allows, and what it does not switch off,
  • raw pointers,
  • what counts as undefined behavior in Rust, especially aliasing,
  • building safe abstractions on top of unsafe code,
  • Miri, an interpreter that finds undefined behavior in tests.

What unsafe unlocks

An unsafe block or function lets you do five extra things:

  1. Dereference a raw pointer (*const T, *mut T).
  2. Call an unsafe function, including all foreign (C) functions.
  3. Access or modify a mutable static.
  4. Implement an unsafe trait (such as Send, Sync, GlobalAlloc).
  5. Access the fields of a union.

That is the whole list. Inside unsafe, the borrow checker, type checker and bounds checks still run as usual. unsafe does not mean "turn off the checks"; it means "I am doing one of these five things, and I promise the invariants the compiler cannot verify".

fn main() {
    let mut values = [1u32, 2, 3, 4];
    let p: *mut u32 = values.as_mut_ptr();   // creating a raw pointer is safe

    unsafe {
        // Dereferencing it is not: we promise p+2 is in bounds and valid.
        *p.add(2) = 30;
        let second = p.add(1).read();
        println!("{second}");
    }
    println!("{values:?}");
}

Raw pointers

*const T and *mut T are C pointers: they can be null, dangling, unaligned, and they alias freely. Creating, copying and comparing them is safe; only reading or writing through them requires unsafe. Convert between references and raw pointers explicitly:

fn main() {
    let x = 5u64;
    let r: &u64 = &x;
    let p: *const u64 = r;                 // reference -> pointer: safe, implicit coercion
    let p2 = &raw const x;                 // or take the address directly
    let back: &u64 = unsafe { &*p };       // pointer -> reference: unsafe
    println!("{} {} {}", back, p == p2, p.is_null());

    // Pointer arithmetic is in elements, like C:
    let arr = [10u16, 20, 30];
    let q = arr.as_ptr();
    let third = unsafe { *q.add(2) };
    let byte_offset = unsafe { (q.add(2) as *const u8).offset_from(q as *const u8) };
    println!("{third} {byte_offset}");
}

Undefined behavior in Rust

Rust's list of undefined behavior overlaps with C++'s, with some notable differences. The ones that matter most:

  • Dereferencing a dangling, null or misaligned pointer.
  • Reading uninitialized memory (use MaybeUninit<T> for memory that starts uninitialized).
  • Producing an invalid value: a bool that is not 0 or 1, an enum with an invalid discriminant, a null reference, a char that is not a Unicode scalar value, a &str that is not UTF-8. In C++ the bad bool is UB only when used; in Rust creating it is already UB.
  • Data races.
  • Breaking the aliasing rules of references.

The last one is the big difference. In C++, the main aliasing rule is strict aliasing: pointers to different types are assumed not to alias. Rust has no type-based aliasing rule at all (you may freely cast a *mut f32 to *mut u32), but it has a much stronger rule about references:

  • While a &mut T is live, no other pointer or reference may access that memory.
  • While a &T is live, the memory must not be written (except inside an UnsafeCell, which is what Cell, RefCell and Mutex are built on).

These are the same guarantees the borrow checker enforces in safe code, and the optimizer relies on them (it is how &mut becomes noalias). In unsafe code you can create two &mut to the same memory from raw pointers, and if you do, the program is undefined even if it seems to work:

fn main() {
    let mut x = 0i32;
    let p = &raw mut x;
    unsafe {
        let a = &mut *p;
        let b = &mut *p;   // UB: two live &mut to the same i32
        *a += 1;
        *b += 1;
    }
}

The rule of thumb: in unsafe code, work with raw pointers, and only create references when you can guarantee the borrow rules for their whole lifetime.

Safe abstractions over unsafe code

The point of unsafe in Rust is not to write unsafe programs. It is to write a small, carefully reviewed unsafe core and wrap it in a safe API, so that no caller, however wrong, can cause undefined behavior. The standard library is built this way: Vec, HashMap, Rc and Mutex all contain unsafe code, and none of their public safe methods can be misused into UB.

Here is a small example: a fixed-capacity, stack-allocated vector (like boost::static_vector), built on uninitialized memory.

use std::mem::MaybeUninit;

pub struct StackVec<T, const N: usize> {
    len: usize,
    items: [MaybeUninit<T>; N],  // invariant: items[..len] are initialized
}

impl<T, const N: usize> StackVec<T, N> {
    pub fn new() -> Self {
        StackVec { len: 0, items: [const { MaybeUninit::uninit() }; N] }
    }

    pub fn push(&mut self, value: T) -> Result<(), T> {
        if self.len == N {
            return Err(value);           // full: give the value back
        }
        self.items[self.len].write(value);
        self.len += 1;
        Ok(())
    }

    pub fn pop(&mut self) -> Option<T> {
        if self.len == 0 {
            return None;
        }
        self.len -= 1;
        // SAFETY: items[len] was initialized (it was below the old len),
        // and decrementing len first means we never read it again.
        Some(unsafe { self.items[self.len].assume_init_read() })
    }

    pub fn as_slice(&self) -> &[T] {
        // SAFETY: items[..len] are initialized, and MaybeUninit<T> has the same layout as T.
        unsafe { std::slice::from_raw_parts(self.items.as_ptr() as *const T, self.len) }
    }
}

impl<T, const N: usize> Drop for StackVec<T, N> {
    fn drop(&mut self) {
        while self.pop().is_some() {}   // drop the initialized elements
    }
}

fn main() {
    let mut v: StackVec<String, 4> = StackVec::new();
    for w in ["a", "b", "c", "d", "e"] {
        if let Err(rejected) = v.push(w.to_string()) {
            println!("full, rejected {rejected}");
        }
    }
    println!("{:?}", v.as_slice());
    println!("{:?}", v.pop());
}

Notice the pattern:

  • The invariant (items[..len] are initialized) is written down and maintained by every method.
  • Each unsafe block has a // SAFETY: comment saying why the invariant makes it sound. This is a strong convention in Rust code reviews, and Clippy can require it (clippy::undocumented_unsafe_blocks).
  • The fields are private, so code outside the module cannot break the invariant. Privacy is what makes the abstraction safe.
  • The public API is entirely safe. Callers cannot misuse it into UB.

When reviewing Rust code, you audit the unsafe blocks and the module that contains them. Everything else is checked by the compiler. In a C++ code review, every line is potentially unsafe.

Miri: finding UB in tests

Miri is an interpreter for Rust's mid-level IR that checks every memory access against the rules above: use after free, out-of-bounds, uninitialized reads, invalid values, and aliasing violations. It is like running AddressSanitizer, MemorySanitizer and UBSan together, with an aliasing checker none of them have:

rustup +nightly component add miri
cargo +nightly miri test

Run your test suite under Miri for any crate that contains unsafe code. It is slow (100 times or more), so run it on unit tests, not your game. On the Playground, Tools → Miri runs it on the current example; try it on the "two &mut" program above.

Engine note

Real engines written in Rust contain unsafe code in a few well-defined places: FFI to graphics APIs, SIMD intrinsics, custom allocators, lock-free queues, and ECS storage. The rest, usually more than 95% of the code, is safe. Aim for the same: concentrate unsafe into small modules with clear invariants and safe interfaces, and keep game code free of it.

Summary

C++Rust
Every line may have UBUB only possible inside unsafe (and the code it relies on)
T**const T / *mut T
Strict aliasing (type-based)No type-based rule; &mut is exclusive, & is read-only
std::launder, placement new, uninitialized storageMaybeUninit<T>
reinterpret_castas between raw pointers; std::mem::transmute
ASan / MSan / UBSanMiri (plus the sanitizers, which also work)
Comments explaining why a cast is OK// SAFETY: comments, linted

Exercises

  1. Run the "two &mut" program under Miri on the Playground and read the report. Rewrite it to use only the raw pointer p for both increments. Does Miri accept it?
  2. Add an fn as_mut_slice(&mut self) -> &mut [T] and an fn clear(&mut self) to StackVec, with SAFETY comments.
  3. StackVec::pop decrements len before reading. What could go wrong if it read first and the element's Drop panicked later? (Hint: think about what Drop for StackVec would then do.)

FFI with C and C++

Your engine already has millions of lines of C and C++, and every graphics API, platform layer and middleware library speaks C. Rust talks to C directly, with no wrapper layer and no overhead: a call from Rust to a C function is the same machine-level call a C program would make. This chapter covers both directions, the tools that generate bindings, and how to bring Rust into an existing CMake project.

This chapter covers:

  • calling C functions, and the types to use at the boundary,
  • callbacks from C into Rust,
  • generating bindings with bindgen,
  • exposing Rust to C and C++ with cbindgen,
  • C++ interop with cxx,
  • linking: build.rs, static and dynamic libraries, and Corrosion for CMake,
  • ownership across the boundary.

Calling C

Declare foreign functions in an extern "C" block. In the 2024 edition the block is marked unsafe extern, because the compiler cannot check that your declaration matches the real function:

use std::ffi::{CStr, CString, c_char, c_int, c_void};

unsafe extern "C" {
    fn strlen(s: *const c_char) -> usize;
    fn abs(x: c_int) -> c_int;
    fn qsort(
        base: *mut c_void,
        n: usize,
        size: usize,
        cmp: extern "C" fn(*const c_void, *const c_void) -> c_int,
    );
}

// A Rust function with the C calling convention, usable as a C callback.
extern "C" fn cmp_floats(a: *const c_void, b: *const c_void) -> c_int {
    // SAFETY: qsort passes pointers to elements of our f32 array.
    let (a, b) = unsafe { (*(a as *const f32), *(b as *const f32)) };
    a.total_cmp(&b) as c_int
}

fn main() {
    let name = CString::new("u_projection").unwrap();
    let len = unsafe { strlen(name.as_ptr()) };
    let a = unsafe { abs(-7) };

    let mut depths = [3.5f32, -1.0, 2.25, 0.0];
    unsafe {
        qsort(depths.as_mut_ptr() as *mut c_void, depths.len(), size_of::<f32>(), cmp_floats);
    }

    let back: &CStr = name.as_c_str();
    println!("{len} {a} {depths:?} {:?}", back.to_str());
}

These particular functions are in the C runtime that every Rust program links anyway. For other libraries you tell the linker what to link (below).

Types at the boundary

Use only FFI-safe types in extern signatures:

CRust
int, unsigned, long, charc_int, c_uint, c_long, c_char (from std::ffi)
int32_t, uint64_t, float, doublei32, u64, f32, f64
size_tusize
bool (C99)bool
T*, const T**mut T, *const T
T* that is never null&T / &mut T / NonNull<T> (if you can guarantee it)
T* that may be nullOption<&T>, Option<NonNull<T>>, or a raw pointer
const char* (string)*const c_char; convert with CStr / CString
void**mut c_void
Function pointerextern "C" fn(...) -> ... (or Option<...> if nullable)
struct#[repr(C)] struct
enum#[repr(C)]/#[repr(i32)] enum only if C can never pass other values; otherwise an integer and constants
Opaque handle (struct VkDevice_T*)A pointer to an opaque #[repr(C)] struct with a private zero-sized field

String, Vec, &str, slices, Box<dyn Trait>, trait objects and Rust enums with data have no stable C representation. Pass pointer-and-length pairs instead.

Enums from C

A Rust enum must only ever hold one of its declared values; anything else is undefined behavior. C APIs regularly return values that were not in the header you compiled against (a newer driver adds a VkResult). So do not declare C enums as Rust enums in FFI signatures. Bindgen's default is to emit them as integer constants for exactly this reason.

Generating bindings with bindgen

Writing declarations by hand is error-prone for real libraries. bindgen reads C headers through libclang and generates the Rust declarations, usually from build.rs:

// build.rs
fn main() {
    println!("cargo::rerun-if-changed=wrapper.h");
    println!("cargo::rustc-link-lib=dylib=physics");          // link libphysics
    println!("cargo::rustc-link-search=native=third_party/physics/lib");

    let bindings = bindgen::Builder::default()
        .header("wrapper.h")                                   // #include "physics.h"
        .allowlist_function("ph_.*")                           // only what we need
        .allowlist_type("ph_.*")
        .generate()
        .expect("bindgen failed");
    let out = std::path::PathBuf::from(std::env::var("OUT_DIR").unwrap());
    bindings.write_to_file(out.join("physics_sys.rs")).unwrap();
}
// src/lib.rs of a `physics-sys` crate
#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals)]
include!(concat!(env!("OUT_DIR"), "/physics_sys.rs"));

By convention a crate named foo-sys contains only the raw bindings and the linking logic, and a separate foo crate wraps them in a safe API. You will see this pattern across the ecosystem: ash (Vulkan), glfw-sys, sdl2-sys, openxr-sys.

Wrapping a C API safely

The safe wrapper is where Rust pays off: you encode the C library's rules (creation and destruction pairing, which objects must outlive which, which calls are thread-safe) in Rust types. A sketch for a physics library with opaque handles:

// --- what bindgen would generate (stubbed so the example runs) ---
#[allow(non_camel_case_types)]
mod sys {
    #[repr(C)]
    pub struct ph_world { _private: [u8; 0] }   // opaque type
    pub unsafe fn ph_world_create(gravity: f32) -> *mut ph_world {
        println!("ph_world_create({gravity})");
        Box::into_raw(Box::new([0u8; 1])) as *mut ph_world
    }
    pub unsafe fn ph_world_step(_w: *mut ph_world, dt: f32) -> i32 {
        if dt > 0.0 { 0 } else { -1 }
    }
    pub unsafe fn ph_world_destroy(w: *mut ph_world) {
        println!("ph_world_destroy");
        drop(unsafe { Box::from_raw(w as *mut [u8; 1]) });
    }
}

// --- the safe wrapper ---
use std::ptr::NonNull;

pub struct World {
    raw: NonNull<sys::ph_world>,   // never null while World exists
}

#[derive(Debug)]
pub struct StepError(i32);

impl World {
    pub fn new(gravity: f32) -> Option<World> {
        let raw = unsafe { sys::ph_world_create(gravity) };
        NonNull::new(raw).map(|raw| World { raw })   // null -> None
    }

    // &mut self: the C library says a world must not be stepped concurrently,
    // and &mut makes that a compile-time guarantee.
    pub fn step(&mut self, dt: f32) -> Result<(), StepError> {
        match unsafe { sys::ph_world_step(self.raw.as_ptr(), dt) } {
            0 => Ok(()),
            code => Err(StepError(code)),
        }
    }
}

impl Drop for World {
    fn drop(&mut self) {
        unsafe { sys::ph_world_destroy(self.raw.as_ptr()) };
    }
}

fn main() {
    let mut world = World::new(-9.81).expect("could not create world");
    world.step(1.0 / 60.0).unwrap();
    println!("{:?}", world.step(-1.0));
}   // destroyed exactly once, here

The wrapper makes the C API's rules impossible to break: you cannot forget to destroy the world, destroy it twice, use it after destroying it, or step it from two threads at once. Note that World is automatically neither Send nor Sync because it holds a raw pointer; if the C library allows using a world from another thread, you add unsafe impl Send for World {} and document why.

Exposing Rust to C and C++

To be callable from C, a Rust function needs the C ABI and an unmangled name:

use std::ffi::{CStr, c_char};

/// Returns the number of vertices in an OBJ file's text, or -1 on error.
#[unsafe(no_mangle)]
pub extern "C" fn obj_count_vertices(text: *const c_char) -> i64 {
    if text.is_null() {
        return -1;
    }
    // SAFETY: the caller promises a valid NUL-terminated string.
    let Ok(s) = unsafe { CStr::from_ptr(text) }.to_str() else {
        return -1;
    };
    s.lines().filter(|l| l.starts_with("v ")).count() as i64
}

fn main() {
    let src = c"v 0 0 0\nv 1 0 0\nf 1 2 3\n";      // a C string literal
    println!("{}", obj_count_vertices(src.as_ptr()));
}

Build the crate as crate-type = ["staticlib"] or ["cdylib"] (Cargo) and link the result into your C++ program. cbindgen generates the matching C or C++ header from the Rust source, the reverse of bindgen.

Never let a panic unwind across an extern "C" boundary into C++. Since Rust 1.81, a panic that would unwind out of an extern "C" function aborts the process instead, which is safe but abrupt. Catch errors and return error codes at the boundary.

C++ interop with cxx

C has a stable ABI; C++ does not. Calling C++ classes, templates or std::string directly from Rust is not possible. The cxx crate provides a safe, zero-overhead bridge for a declared subset: you describe the shared interface once in Rust, and cxx generates both the Rust and the C++ glue, checking at compile time that both sides match.

#[cxx::bridge]
mod ffi {
    // Shared struct, visible to both languages.
    struct MeshInfo {
        name: String,
        vertex_count: u32,
    }

    unsafe extern "C++" {
        include!("engine/asset_db.h");
        type AssetDb;                                  // an opaque C++ class
        fn open_asset_db(path: &str) -> UniquePtr<AssetDb>;
        fn mesh_info(self: &AssetDb, id: u64) -> MeshInfo;
    }

    extern "Rust" {
        fn validate_mesh(info: &MeshInfo) -> bool;     // callable from C++
    }
}

fn validate_mesh(info: &ffi::MeshInfo) -> bool {
    info.vertex_count > 0 && !info.name.is_empty()
}

cxx understands std::unique_ptr, std::shared_ptr, std::string, std::vector and rust::String/rust::Vec/rust::Slice on the C++ side. For large existing C++ APIs, autocxx generates cxx bridges from headers.

Rust inside a CMake project

To introduce Rust into an existing C++ engine incrementally, add a Rust crate as a library and let CMake drive Cargo. Corrosion does this:

include(FetchContent)
FetchContent_Declare(Corrosion
    GIT_REPOSITORY https://github.com/corrosion-rs/corrosion.git
    GIT_TAG v0.5)
FetchContent_MakeAvailable(Corrosion)

corrosion_import_crate(MANIFEST_PATH rust/asset_tools/Cargo.toml)

add_executable(editor src/main.cpp)
target_link_libraries(editor PRIVATE asset_tools)   # the Rust staticlib

A common first project is a self-contained subsystem with a narrow interface: an asset importer, a file-format parser, a networking layer, or a tool. Those benefit most from Rust's safety (they handle untrusted input) and need the least interop.

Ownership across the boundary

The rules you follow in C APIs still apply, and Rust gives you tools to state them:

  • Memory allocated by Rust must be freed by Rust, and memory from C by C. Export a free function: Box::into_raw hands a pointer to C, and Box::from_raw in your xxx_destroy function takes it back.
  • Strings: pass *const c_char in (borrowed, via CStr) and return either a pointer into Rust-owned storage that C must not free, or a CString turned into a raw pointer with a matching free_string function.
  • Callbacks with context: pass a *mut c_void user pointer alongside an extern "C" fn, and cast it back to the right type in the callback.

Summary

C / C++Rust
Declaring a C functionunsafe extern "C" { fn f(...); }
Function pointer callbackextern "C" fn(...)
extern "C" + __declspec(dllexport)#[unsafe(no_mangle)] pub extern "C" fn
Writing headers for bindingsbindgen (C → Rust), cbindgen (Rust → C)
C++ class interopcxx, autocxx
char* stringsCStr (borrowed), CString (owned), c"..." literals
target_link_librariescargo::rustc-link-lib in build.rs
Rust library in CMakeCorrosion

Exercises

  1. Use qsort from the C library to sort an array of #[repr(C)] struct DrawItem { key: u64, mesh: u32 } by key.
  2. Write #[unsafe(no_mangle)] extern "C" functions counter_new, counter_increment and counter_free that manage a Box<u64> across the boundary, and a Rust main that calls them the way C would.
  3. In the World wrapper, add a Body type created by World that must not outlive it. Give Body a lifetime parameter tied to the world (Body<'w>) and check that dropping the world first does not compile.

Macros

The C preprocessor is a text substitution engine that knows nothing about C++: it ignores scopes, evaluates arguments more than once, and produces errors in code you never wrote. C++ programmers learn to minimize it and move what they can into templates and constexpr. Rust macros are different in kind. They operate on the syntax tree, they are hygienic (they cannot accidentally capture or shadow your variables), and they are used routinely: println!, vec!, format! and #[derive] are all macros.

This chapter covers:

  • declarative macros with macro_rules!,
  • hygiene, and why the classic preprocessor bugs cannot happen,
  • derive, attribute and function-like procedural macros,
  • when to write a macro, and when a generic or const fn is better.

macro_rules!

A declarative macro is a set of pattern-and-template rules matched against the macro's input tokens:

/// Build a HashMap from `key => value` pairs.
macro_rules! hashmap {
    () => { std::collections::HashMap::new() };
    ( $( $key:expr => $value:expr ),+ $(,)? ) => {{
        let mut m = std::collections::HashMap::new();
        $( m.insert($key, $value); )+
        m
    }};
}

fn main() {
    let empty: std::collections::HashMap<u8, u8> = hashmap!();
    let formats = hashmap! {
        "png" => 4,
        "jpg" => 3,
        "exr" => 16,
    };
    println!("{} {:?}", empty.len(), formats.get("exr"));
}

The pieces:

  • $key:expr captures a fragment of a specific syntactic kind. Common kinds: expr, ident (a name), ty (a type), tt (any single token tree), literal, pat, block, item.
  • $( ... ),+ repeats one or more times with a comma separator (* for zero or more, ? for optional). The same $( ... )+ in the template repeats the output once per match.
  • Rules are tried in order, like match arms.

Because fragments are parsed syntax, not text, $key is always a complete expression. Passing a + b to a macro that computes $x * 2 gives (a + b) * 2, never a + b * 2.

Hygiene

macro_rules! square {
    ($x:expr) => {{
        let tmp = $x;      // evaluated once, into a local the caller cannot see
        tmp * tmp
    }};
}

fn main() {
    let tmp = 3;
    let mut calls = 0;
    let mut next = || { calls += 1; 4 };
    println!("{}", square!(tmp + 1));   // 16, not affected by the macro's own `tmp`
    println!("{}", square!(next()));     // 16, and next() runs once
    println!("calls = {calls}");
}

Both classic preprocessor bugs are gone. The macro's tmp and the caller's tmp are different variables (hygiene), and the argument is evaluated once because the macro binds it to a local, which it can do because it expands to a block expression rather than raw text.

A practical example: reducing boilerplate

Macros shine when you need to generate many similar items, the kind of code C++ engines generate with X-macros or external scripts. For example, implementing the same operators for several vector types:

use std::ops::{Add, Mul, Sub};

macro_rules! impl_vec_ops {
    ($name:ident { $($field:ident),+ }) => {
        #[derive(Debug, Clone, Copy, PartialEq, Default)]
        pub struct $name { $(pub $field: f32),+ }

        impl Add for $name {
            type Output = $name;
            fn add(self, o: $name) -> $name { $name { $($field: self.$field + o.$field),+ } }
        }
        impl Sub for $name {
            type Output = $name;
            fn sub(self, o: $name) -> $name { $name { $($field: self.$field - o.$field),+ } }
        }
        impl Mul<f32> for $name {
            type Output = $name;
            fn mul(self, s: f32) -> $name { $name { $($field: self.$field * s),+ } }
        }
        impl $name {
            pub fn dot(self, o: $name) -> f32 { 0.0 $(+ self.$field * o.$field)+ }
        }
    };
}

impl_vec_ops!(Vec2 { x, y });
impl_vec_ops!(Vec3 { x, y, z });
impl_vec_ops!(Vec4 { x, y, z, w });

fn main() {
    let a = Vec3 { x: 1.0, y: 2.0, z: 3.0 };
    let b = Vec4 { x: 1.0, ..Default::default() };
    println!("{:?} {} {}", a + a * 2.0, a.dot(a), b.dot(b));
}

To see what a macro expands to, use cargo expand (the cargo-expand tool), or Tools → Expand macros on the Playground. That is the equivalent of -E, but the output is formatted Rust.

Procedural macros

Procedural macros are Rust functions, compiled as a separate crate, that take a token stream and return a token stream. They run inside the compiler and can do arbitrary analysis. There are three kinds:

KindSyntaxExample
Derive#[derive(Serialize)] on a struct or enumserde, bytemuck::Pod, thiserror::Error
Attribute#[my_attr(...)] on an item#[tokio::main], #[test]-like frameworks, profiling instrumentation
Function-likemy_macro!(...)sqlx::query! (checks SQL at compile time), include_wgsl!

The most important use for an engine is derive, which replaces most of what C++ engines do with reflection systems, code generators and REFLECT() macros:

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct LightComponent {
    color: [f32; 3],
    intensity: f32,
    #[serde(default)]
    casts_shadows: bool,
    #[serde(skip)]
    shadow_map: Option<TextureHandle>,   // runtime-only, not saved
}

// Now LightComponent can be read and written as JSON, RON, TOML, bincode, ...
let light: LightComponent = ron::from_str("(color: (1, 0.9, 0.8), intensity: 4.0)")?;

The derive sees the struct definition (field names, types, attributes) at compile time and generates the serialization code. No runtime type information, no registration step, no separate code generator in the build.

Writing your own procedural macro uses the syn (parse Rust syntax) and quote (generate Rust code) crates. It is a moderately advanced topic and worth it for engine-wide patterns, such as deriving editor inspectors or component registration.

Macro, generic, or const fn?

  • Use a function or generic when you can. They type-check, show up properly in documentation, and give better error messages.
  • Use const fn for compile-time computation (lookup tables, hashing string IDs at compile time).
  • Use macro_rules! when you need something functions cannot do: a variable number of arguments, generating items (structs, impls), or taking syntax that is not a value (field names, types).
  • Use a derive macro to generate trait implementations from a type's structure: serialization, reflection, GPU layout checks.

Summary

C / C++Rust
#define text substitutionmacro_rules! on syntax trees, hygienic
#includemod / use (no textual inclusion)
#ifdef#[cfg(...)] attributes
Variadic macros, X-macrosRepetitions $( ... ),*
Reflection macros / code generatorsDerive macros (serde, bytemuck, custom)
cpp -Ecargo expand
__FILE__, __LINE__file!(), line!(), module_path!()
static_assertconst _: () = assert!(...);

Exercises

  1. Write macro_rules! max! that accepts one or more expressions and returns the largest, evaluating each argument exactly once.
  2. Add a length method to impl_vec_ops! using dot.
  3. Write a const fn fnv1a(s: &str) -> u64 and use it to define const PLAYER_TAG: u64 = fnv1a("player");. Compare with doing it in a macro.

Testing, benchmarks and tooling

In C++ you choose a test framework (GoogleTest, Catch2, doctest), a benchmark library, a formatter, a linter and a documentation generator, then wire them into CMake. Rust ships with all of them, and every Rust project uses the same ones, so cargo test works in any repository you clone.

This chapter covers:

  • unit tests, integration tests and documentation tests,
  • testing things that should panic, and tests that return Result,
  • benchmarks with criterion,
  • property-based testing and fuzzing,
  • rustfmt, Clippy and rustdoc,
  • a CI setup.

Unit tests

Unit tests live in the same file as the code, in a module compiled only for tests:

pub fn aabb_overlap(a: ([f32; 2], [f32; 2]), b: ([f32; 2], [f32; 2])) -> bool {
    a.0[0] < b.1[0] && b.0[0] < a.1[0] && a.0[1] < b.1[1] && b.0[1] < a.1[1]
}

fn clamp01(x: f32) -> f32 {          // private functions are testable too
    x.max(0.0).min(1.0)
}

#[cfg(test)]
mod tests {
    use super::*;                     // everything from the parent module, private items included

    #[test]
    fn overlapping_boxes() {
        assert!(aabb_overlap(([0.0, 0.0], [2.0, 2.0]), ([1.0, 1.0], [3.0, 3.0])));
    }

    #[test]
    fn touching_edges_do_not_overlap() {
        assert!(!aabb_overlap(([0.0, 0.0], [1.0, 1.0]), ([1.0, 0.0], [2.0, 1.0])));
    }

    #[test]
    fn clamps() {
        assert_eq!(clamp01(-1.0), 0.0);
        assert_eq!(clamp01(0.25), 0.25);
        assert_eq!(clamp01(7.0), 1.0, "values above 1 must clamp");
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn out_of_range_panics() {
        let v = vec![1, 2, 3];
        let i = v.len();
        let _ = v[i];
    }

    #[test]
    fn parse_or_fail() -> Result<(), std::num::ParseIntError> {
        let n: i32 = "42".parse()?;   // tests may return Result and use ?
        assert_eq!(n, 42);
        Ok(())
    }

    #[test]
    #[ignore = "slow: run with cargo test -- --ignored"]
    fn bake_lightmap() {}
}
fn main() {}

cargo test builds the crate in test mode, runs every #[test] function on a thread pool in parallel, and reports results. Useful variations:

cargo test                     # everything
cargo test overlap             # only tests whose name contains "overlap"
cargo test -- --nocapture      # show println! output from passing tests
cargo test -- --test-threads=1 # run serially (tests sharing a GPU, say)
cargo test --release           # optimized build

Because unit tests are inside the module, they can test private functions without the #define private public tricks or friend declarations C++ tests sometimes resort to.

Integration tests

Files in a top-level tests/ directory are compiled as separate crates that use your library through its public API only, like an external user:

my-engine/
├── src/lib.rs
└── tests/
    ├── load_scene.rs
    └── common/mod.rs     # shared helpers (not a test file itself)
// tests/load_scene.rs
use my_engine::scene::Scene;

#[test]
fn loads_sample_scene() {
    let scene = Scene::load("tests/data/sample.ron").unwrap();
    assert_eq!(scene.entities().count(), 12);
}

Documentation tests

Code examples in documentation comments are compiled and run by cargo test, so documentation cannot rot:

/// Linearly interpolates between `a` and `b`.
///
/// ```
/// # use mylib::lerp;   // hidden line: not shown in the docs
/// assert_eq!(lerp(0.0, 10.0, 0.25), 2.5);
/// ```
pub fn lerp(a: f32, b: f32, t: f32) -> f32 {
    a + (b - a) * t
}
fn main() { assert_eq!(lerp(0.0, 10.0, 0.25), 2.5); }

Every example in this book is tested the same way: the build runs mdbook test, which compiles and runs each one as a doc test.

Benchmarks

The standard benchmark harness is still unstable, so the community standard is criterion, which runs each benchmark enough times for statistically sound results and reports changes against the previous run:

// benches/culling.rs   (with [[bench]] name = "culling", harness = false in Cargo.toml)
use criterion::{criterion_group, criterion_main, Criterion};
use std::hint::black_box;

fn bench_frustum(c: &mut Criterion) {
    let boxes = make_random_aabbs(10_000);
    let frustum = Frustum::from_view_proj(&camera_matrix());
    c.bench_function("cull 10k aabbs", |b| {
        b.iter(|| frustum.cull(black_box(&boxes)))
    });
}

criterion_group!(benches, bench_frustum);
criterion_main!(benches);

cargo bench runs them. std::hint::black_box stops the optimizer from deleting the work, like benchmark::DoNotOptimize.

Property tests and fuzzing

  • proptest and quickcheck generate random inputs and shrink failures to a minimal case: "for all vectors v, normalize(v).length() is 1 or v is zero".
  • cargo-fuzz runs libFuzzer against a function that takes &[u8]. Point it at every parser of untrusted data: asset formats, network packets, save files. Fuzzing safe Rust finds panics and logic bugs; fuzzing unsafe Rust, combined with sanitizers, finds memory bugs.

Formatting, linting and docs

ToolCommandC++ analogue
rustfmtcargo fmt (--check in CI)clang-format
Clippycargo clippy (-- -D warnings in CI)clang-tidy
rustdoccargo doc --openDoxygen
cargo-deny / cargo-auditcargo deny checkLicense and vulnerability scanners

rustfmt has one standard style with few options, and almost every Rust project uses it, so all Rust code looks alike. Format on save and stop discussing style.

Clippy has hundreds of lints, from correctness (clippy::eq_op: x == x) to performance (clippy::large_enum_variant) and style. It is quite good at teaching idiomatic Rust: when it suggests a rewrite, read why. Configure lints in Cargo.toml:

[lints.clippy]
undocumented_unsafe_blocks = "warn"
too_many_arguments = "allow"

rustdoc builds HTML documentation from /// comments, including your dependencies' documentation, all cross-linked. Every crate on crates.io has its documentation on docs.rs.

A CI setup

A typical GitHub Actions job for a Rust project:

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy
      - uses: Swatinem/rust-cache@v2
      - run: cargo fmt --check
      - run: cargo clippy --all-targets -- -D warnings
      - run: cargo test --all-targets

Summary

C++Rust
GoogleTest / Catch2Built-in #[test], cargo test
EXPECT_EQ, ASSERT_TRUEassert_eq!, assert! (with optional messages)
EXPECT_DEATH#[should_panic]
Test executables registered in CMaketests/ directory, discovered automatically
Google Benchmarkcriterion
libFuzzercargo-fuzz
clang-format / clang-tidyrustfmt / Clippy
Doxygenrustdoc; examples are tested

Exercises

  1. Add tests for aabb_overlap covering boxes that contain each other and boxes with zero area. Do your tests pass? Should they?
  2. Write a doc test for a fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 showing three example values, and run it with cargo test --doc.
  3. Run cargo clippy on a project from an earlier chapter and fix every warning. Which lint taught you something?

Handles and arenas instead of pointers

Game objects point at each other. A missile tracks its target, a light belongs to a room, a UI widget knows its parent, an animation references a skeleton. In C++ these links are usually raw pointers or shared_ptr/weak_ptr, and the classic bug is a pointer that outlives its object: the enemy dies, its memory is reused for a bullet, and the missile now steers toward the bullet.

The borrowing chapter showed that Rust references are for short-lived access. A &Enemy stored inside a Missile would freeze the whole enemy list for as long as the missile exists. This chapter introduces the pattern most Rust engines use instead, which many C++ engines also use for the same reasons: objects live in an arena, and other objects refer to them by handle.

You will:

  • see why indices alone are not enough, and how a generation counter fixes them,
  • build a small, typed generational arena (about 80 lines),
  • compare it with Rc/Weak and with what C++ engines do,
  • learn which crates to use in real projects.

Handles in one picture

An arena is a Vec of slots that owns every object of one type. A handle is a small Copy value (a slot index plus a generation number) that identifies one object. Every time a slot is freed, its generation goes up, so any handle created before that no longer matches.

Play with it. Start in C++ style, spawn two entities, despawn the first, spawn another (it reuses the free slot), then read through the old pointer. Then switch to handles and do the same.

With plain pointers or indices, reading through a stale reference gives you a valid-looking object, just the wrong one. No sanitizer catches it, because the memory is not freed: it was reused, legitimately. A generation check turns that into an Option you are forced to handle.

You have seen this before

This is the same design as handles in many C++ engines and libraries: Andre Weissflog's "Handles are the better pointers" (the Sokol libraries), versioned entity IDs in EnTT, and VkBuffer itself, which is a handle and not a pointer. Rust did not invent it. What Rust adds is that the alternative, long-lived raw pointers, simply does not compile, so the whole codebase converges on handles.

Building a generational arena

A handle should be typed, so a Handle<Texture> cannot be passed where a Handle<Mesh> is expected, even though both are just two integers. PhantomData adds the type parameter without storing anything:

use std::fmt;
use std::marker::PhantomData;

/// A copyable reference to a `T` stored in an `Arena<T>`. 8 bytes.
pub struct Handle<T> {
    index: u32,
    generation: u32,
    // `fn() -> T` instead of `T`: the handle does not own a T, so it stays
    // Copy, Send and Sync whatever T is.
    _marker: PhantomData<fn() -> T>,
}

// `#[derive(Clone, Copy)]` would require `T: Copy`, so implement them by hand.
impl<T> Clone for Handle<T> {
    fn clone(&self) -> Self { *self }
}
impl<T> Copy for Handle<T> {}
impl<T> PartialEq for Handle<T> {
    fn eq(&self, o: &Self) -> bool {
        self.index == o.index && self.generation == o.generation
    }
}
impl<T> Eq for Handle<T> {}
impl<T> fmt::Debug for Handle<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "#{}g{}", self.index, self.generation)
    }
}

struct Slot<T> {
    generation: u32,
    value: Option<T>,
}

pub struct Arena<T> {
    slots: Vec<Slot<T>>,
    free: Vec<u32>, // indices of empty slots, reused LIFO
    len: usize,
}

impl<T> Arena<T> {
    pub fn new() -> Self {
        Arena { slots: Vec::new(), free: Vec::new(), len: 0 }
    }

    pub fn insert(&mut self, value: T) -> Handle<T> {
        self.len += 1;
        let index = match self.free.pop() {
            Some(i) => {
                self.slots[i as usize].value = Some(value);
                i
            }
            None => {
                self.slots.push(Slot { generation: 0, value: Some(value) });
                (self.slots.len() - 1) as u32
            }
        };
        let generation = self.slots[index as usize].generation;
        Handle { index, generation, _marker: PhantomData }
    }

    /// Removes and returns the value, or `None` if the handle is stale.
    pub fn remove(&mut self, h: Handle<T>) -> Option<T> {
        let slot = self.slots.get_mut(h.index as usize)?;
        if slot.generation != h.generation {
            return None;
        }
        let value = slot.value.take()?;
        slot.generation = slot.generation.wrapping_add(1); // invalidate old handles
        self.free.push(h.index);
        self.len -= 1;
        Some(value)
    }

    pub fn get(&self, h: Handle<T>) -> Option<&T> {
        let slot = self.slots.get(h.index as usize)?;
        if slot.generation == h.generation { slot.value.as_ref() } else { None }
    }

    pub fn get_mut(&mut self, h: Handle<T>) -> Option<&mut T> {
        let slot = self.slots.get_mut(h.index as usize)?;
        if slot.generation == h.generation { slot.value.as_mut() } else { None }
    }

    pub fn len(&self) -> usize {
        self.len
    }

    /// Iterate over live values together with their handles.
    pub fn iter(&self) -> impl Iterator<Item = (Handle<T>, &T)> {
        self.slots.iter().enumerate().filter_map(|(i, s)| {
            let h = Handle { index: i as u32, generation: s.generation, _marker: PhantomData };
            s.value.as_ref().map(|v| (h, v))
        })
    }
}

// ---- a tiny game using it ----

#[derive(Debug)]
struct Enemy {
    name: &'static str,
    hp: i32,
}

struct Missile {
    target: Handle<Enemy>,
    damage: i32,
}

fn main() {
    let mut enemies = Arena::new();
    let orc = enemies.insert(Enemy { name: "orc", hp: 30 });
    let bat = enemies.insert(Enemy { name: "bat", hp: 5 });

    let missiles = vec![
        Missile { target: orc, damage: 10 },
        Missile { target: bat, damage: 10 },
    ];

    // The orc dies before the missiles land, and a goblin spawns in its slot.
    enemies.remove(orc);
    let goblin = enemies.insert(Enemy { name: "goblin", hp: 12 });
    println!("orc was {orc:?}, goblin is {goblin:?}: same slot, new generation");

    for m in &missiles {
        match enemies.get_mut(m.target) {
            Some(e) => {
                e.hp -= m.damage;
                println!("hit {} -> hp {}", e.name, e.hp);
            }
            None => println!("missile aimed at {:?} lost its target", m.target),
        }
    }

    for (h, e) in enemies.iter() {
        println!("{h:?}: {e:?}");
    }
    println!("{} alive", enemies.len());
}

Run it. The missile aimed at the orc reports a lost target instead of hitting the goblin that took the orc's memory.

Notice what the borrow checker is doing here, and what it is not doing:

  • missiles holds handles, not references, so enemies is never frozen. You can insert and remove enemies while missiles exist.
  • get_mut returns a short-lived &mut Enemy. That reference is checked as usual: you cannot keep it across a call to enemies.insert, which might reallocate the Vec. The borrow checker still protects you from the C++ invalidation bug, at the moment of access.
  • The arena is the single owner of every enemy. Dropping the arena drops them all, in one place.
Under the hood: cost and layout
  • A Handle<T> is 8 bytes and Copy. Compared with a 64-bit pointer it is the same size, survives reallocation, and can be serialized, saved to disk, or sent over the network, because it contains no address.
  • Access costs one bounds check, one compare, and one load, all on the same cache line as the value. Rc<RefCell<T>> costs a separate heap allocation per object plus a runtime borrow flag.
  • All enemies sit in one contiguous Vec, which is what you want for iteration in a system update.
  • Option<Handle<T>> is 12 bytes here. If the generation starts at 1 and is stored as NonZeroU32, the compiler uses 0 as the None niche and Option<Handle<T>> becomes 8 bytes too. (That is exercise 2.)

Comparing the options

NeedC++Rust
Temporary access during a callT&, T*&T, &mut T
Single owner, heap allocatedstd::unique_ptr<T>Box<T>
Shared ownership, object lives while anyone holds itstd::shared_ptr<T>Rc<T> / Arc<T>
Observe without keeping alivestd::weak_ptr<T>rc::Weak<T>
Many objects of one type, referenced from many places, lifetime decided by game logicobject pool + handles, or raw pointers and careArena<T> + Handle<T>

Rc/Weak work, and are the right answer for some structures (a shared immutable asset, a UI tree). But for game objects whose lifetime is decided by the game ("the enemy dies when its HP hits zero"), shared ownership is the wrong model: nobody holding a reference should keep a dead enemy alive. The arena makes the owner explicit, and handles make "it might be gone" explicit.

Arenas of a different kind: bump allocation

"Arena" also names a second pattern you may know from C++ frame allocators: allocate many small objects from one big block, then free the whole block at once. In Rust this is the bumpalo crate. It hands out real references whose lifetime is tied to the arena, so the borrow checker proves nothing outlives the frame:

use bumpalo::Bump;

struct DrawCmd {
    mesh: u32,
    instance_count: u32,
}

fn build_frame(frame_alloc: &Bump) {
    // Both allocations live in the arena. The references cannot escape it:
    // their lifetime is tied to `frame_alloc`.
    let cmd: &mut DrawCmd = frame_alloc.alloc(DrawCmd { mesh: 7, instance_count: 1 });
    let visible: &mut [u32] = frame_alloc.alloc_slice_fill_copy(1024, 0);
    cmd.instance_count = visible.len() as u32;
}

fn main() {
    let mut frame_alloc = Bump::new();
    loop {
        build_frame(&frame_alloc);
        frame_alloc.reset(); // free everything from this frame, O(1)
        break;
    }
}

Generational arenas are for long-lived objects with individual lifetimes. Bump arenas are for short-lived scratch data with a shared lifetime. Engines use both.

Crates for real projects

Writing your own arena is a good exercise and fine for small projects. For production, use a maintained crate:

  • slotmap: the most widely used. SlotMap is the design above; DenseSlotMap keeps values packed for faster iteration; SecondaryMap attaches extra per-object data to existing keys, which is a small step toward ECS components.
  • thunderdome: a compact generational arena with 8-byte Option<Index>.
  • bumpalo: bump allocation, as above.

The next step from "an arena per object type, plus handles" is an entity-component system, where the handle is the entity and each component type has its own storage. That is the next chapter.

Exercises

  1. Add fn get2_mut(&mut self, a: Handle<T>, b: Handle<T>) -> Option<(&mut T, &mut T)> that returns two distinct objects mutably (for a collision response, say). Hint: split_at_mut or get_disjoint_mut from the borrowing chapter, and decide what to do when a == b.
  2. Change generation to NonZeroU32 starting at 1 and confirm with std::mem::size_of::<Option<Handle<Enemy>>>() that it shrinks to 8 bytes.
  3. remove uses wrapping_add. After 2³² reuses of one slot, a very old handle could match again. Make a slot retire permanently (never return to the free list) when its generation would wrap. What does that cost?
  4. Make Arena::iter_mut that yields (Handle<T>, &mut T). Why can't it be written by calling get_mut in a loop?

ECS and the borrow checker

The classic object-oriented engine has a GameObject base class, a scene graph of parents and children pointing at each other, and components that hold pointers to their owner and to sibling components. Translate that literally into Rust and you hit the borrow checker on the first day: every object is reachable from several places, and any of those places might want to mutate it.

The entity-component-system pattern (ECS) that many C++ engines adopted for performance happens to be the shape that the borrow checker likes best. This chapter explains why, builds a tiny ECS in about a hundred lines, and then shows the crates real projects use.

This chapter covers:

  • why a graph of mutually pointing objects fights the borrow checker,
  • the struct-of-arrays world and split borrows,
  • a tiny generic ECS with runtime-checked column borrows,
  • archetypes, and the hecs and bevy_ecs crates,
  • running systems in parallel safely.

Why object graphs hurt

Here is a typical C++ scene node:

struct Node {
    Node* parent;
    std::vector<Node*> children;
    Transform local, world;
    std::vector<Component*> components;   // each Component has Node* owner
};

Every pointer here is a second path to the same object. In C++ nothing stops you from updating a child through children[i] while another function holds a Node& to that same child. In Rust, a &mut Node must be the only path to that node for as long as it lives. A literal translation therefore ends up as Rc<RefCell<Node>> everywhere, with Weak for the parent link:

use std::cell::RefCell;
use std::rc::{Rc, Weak};

struct Node {
    name: String,
    parent: RefCell<Weak<Node>>,
    children: RefCell<Vec<Rc<Node>>>,
    local_y: f32,
    world_y: RefCell<f32>,
}

fn update_world(node: &Rc<Node>, parent_y: f32) {
    let y = parent_y + node.local_y;
    *node.world_y.borrow_mut() = y;
    for child in node.children.borrow().iter() {
        update_world(child, y);
    }
}

fn main() {
    let root = Rc::new(Node {
        name: "root".into(), parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![]), local_y: 1.0, world_y: RefCell::new(0.0),
    });
    let arm = Rc::new(Node {
        name: "arm".into(), parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![]), local_y: 2.0, world_y: RefCell::new(0.0),
    });
    *arm.parent.borrow_mut() = Rc::downgrade(&root);
    root.children.borrow_mut().push(arm.clone());

    update_world(&root, 0.0);
    let parent = arm.parent.borrow().upgrade().unwrap();
    println!("{} world y = {}, parent = {}", arm.name, arm.world_y.borrow(), parent.name);
}

It works, but look at the cost. Every node is a separate heap allocation with a reference count, every field access goes through a runtime borrow flag, a mistake becomes a BorrowMutError panic instead of a compile error, and the data is scattered across the heap, which is the cache behavior ECS was invented to avoid. This is a sign that the design is fighting the language, not that Rust cannot express it.

C++ habit to unlearn

If you find yourself writing Rc<RefCell<...>> for most of your game objects, stop and restructure. Put objects in arenas or component storage, refer to them by handle, and pass the storage (not the object) to the code that needs it.

Step 1: a world of columns

The simplest ECS is a struct of arrays. An entity is an index; each component type is a column; a missing component is None:

#[derive(Clone, Copy, Debug)]
struct Position { x: f32, y: f32 }
#[derive(Clone, Copy, Debug)]
struct Velocity { x: f32, y: f32 }
#[derive(Clone, Copy, Debug)]
struct Health(i32);

#[derive(Default)]
struct World {
    positions: Vec<Option<Position>>,
    velocities: Vec<Option<Velocity>>,
    health: Vec<Option<Health>>,
}

impl World {
    fn spawn(&mut self, p: Option<Position>, v: Option<Velocity>, h: Option<Health>) -> usize {
        self.positions.push(p);
        self.velocities.push(v);
        self.health.push(h);
        self.positions.len() - 1
    }
}

// A system is a function that borrows exactly the columns it needs.
fn movement(positions: &mut [Option<Position>], velocities: &[Option<Velocity>], dt: f32) {
    for (p, v) in positions.iter_mut().zip(velocities) {
        if let (Some(p), Some(v)) = (p, v) {
            p.x += v.x * dt;
            p.y += v.y * dt;
        }
    }
}

fn poison(health: &mut [Option<Health>]) {
    for h in health.iter_mut().flatten() {
        h.0 -= 1;
    }
}

fn main() {
    let mut world = World::default();
    let player = world.spawn(Some(Position { x: 0.0, y: 0.0 }), Some(Velocity { x: 1.0, y: 0.5 }), Some(Health(10)));
    let rock = world.spawn(Some(Position { x: 5.0, y: 5.0 }), None, None);

    // Split borrows: &mut to one field and & to another at the same time is fine.
    movement(&mut world.positions, &world.velocities, 0.016);
    poison(&mut world.health);

    println!("player {:?} {:?}", world.positions[player], world.health[player]);
    println!("rock   {:?}", world.positions[rock]);
}

Two things make this pleasant in Rust:

  • Split borrows. &mut world.positions and &world.velocities borrow different fields, so the compiler allows both at once. This is the same rule that lets the particle loop in Memory and performance vectorize: the compiler knows the slices do not alias.
  • Systems declare their access in their signature. movement cannot touch health; poison cannot touch positions. You can read a system's data dependencies from its parameter list.

What this version lacks is extensibility: every component type is a field of World, and despawning leaves holes. Despawning is solved with generations, exactly as in the arena chapter. Extensibility needs type erasure.

Step 2: a generic world

A reusable ECS cannot know the component types in advance. It stores one column per type in a map keyed by TypeId, with the column type-erased as Box<dyn Any>. Each column sits inside a RefCell, so that a query can borrow the Position column mutably and the Velocity column immutably at the same time, through a shared &World:

use std::any::{Any, TypeId};
use std::cell::{Ref, RefCell, RefMut};
use std::collections::HashMap;

type Entity = usize;

#[derive(Default)]
struct World {
    next: Entity,
    columns: HashMap<TypeId, Box<dyn Any>>, // each value is a RefCell<Vec<Option<T>>>
}

impl World {
    fn spawn(&mut self) -> Entity {
        self.next += 1;
        self.next - 1
    }

    fn insert<T: 'static>(&mut self, e: Entity, value: T) {
        let column = self
            .columns
            .entry(TypeId::of::<T>())
            .or_insert_with(|| Box::new(RefCell::new(Vec::<Option<T>>::new())))
            .downcast_mut::<RefCell<Vec<Option<T>>>>()
            .expect("column type matches its TypeId");
        let column = column.get_mut();          // &mut World: no runtime check needed
        if column.len() <= e {
            column.resize_with(e + 1, || None);
        }
        column[e] = Some(value);
    }

    fn column<T: 'static>(&self) -> &RefCell<Vec<Option<T>>> {
        self.columns
            .get(&TypeId::of::<T>())
            .and_then(|c| c.downcast_ref())
            .expect("no such component type")
    }

    fn read<T: 'static>(&self) -> Ref<'_, Vec<Option<T>>> {
        self.column::<T>().borrow()
    }

    fn write<T: 'static>(&self) -> RefMut<'_, Vec<Option<T>>> {
        self.column::<T>().borrow_mut()
    }
}

#[derive(Debug)]
struct Position(f32, f32);
#[derive(Debug)]
struct Velocity(f32, f32);
struct Name(&'static str);

fn movement(world: &World, dt: f32) {
    let mut positions = world.write::<Position>();
    let velocities = world.read::<Velocity>();
    for (p, v) in positions.iter_mut().zip(velocities.iter()) {
        if let (Some(p), Some(v)) = (p, v) {
            p.0 += v.0 * dt;
            p.1 += v.1 * dt;
        }
    }
}

fn report(world: &World) {
    let names = world.read::<Name>();
    let positions = world.read::<Position>();
    for (n, p) in names.iter().zip(positions.iter()) {
        if let (Some(n), Some(p)) = (n, p) {
            println!("{:>6} at {:?}", n.0, p);
        }
    }
}

fn main() {
    let mut world = World::default();
    let ship = world.spawn();
    world.insert(ship, Name("ship"));
    world.insert(ship, Position(0.0, 0.0));
    world.insert(ship, Velocity(10.0, 0.0));
    let buoy = world.spawn();
    world.insert(buoy, Name("buoy"));
    world.insert(buoy, Position(3.0, 4.0));

    movement(&world, 0.5);
    report(&world);
}

This is the trade most ECS libraries make internally. The compiler cannot see which columns a query will touch, because the types are chosen at run time through a map, so the borrow rules move to run time: a system that asks for write::<Position>() twice panics with "already borrowed" instead of creating two aliasing &mut. The guarantee is the same as the compiler's (never two mutable paths to the same column), only checked later. Real libraries check these conflicts once, when a query or system is created, rather than on every access.

Under the hood

Box<dyn Any> plus downcast_ref is Rust's checked equivalent of storing a void* next to a type ID and static_casting it back. downcast_ref compares TypeIds and returns None on mismatch, so a bug gives you a clean panic instead of reinterpreting memory.

Archetypes

Columns of Option<T> indexed by entity waste memory when components are sparse, and a query over two components still walks every entity. Production ECS libraries (Unity DOTS, flecs, bevy_ecs, hecs) use archetypes instead: all entities with exactly the same set of component types are stored together, in one table with a dense column per type.

ArchetypeColumns (dense, same length)Entities
{Position, Velocity}Vec<Position>, Vec<Velocity>ship, bullet 1, bullet 2
{Position, Name}Vec<Position>, Vec<Name>buoy
{Position, Velocity, Health}three columnsplayer

A query for (&mut Position, &Velocity) visits only the tables whose archetype contains both types, and inside each table zips two dense slices: the same tight loop as the struct-of-arrays version, with no Option checks. Adding or removing a component moves the entity to a different table, which is the cost of the design. An entity ID maps to (table, row) through a small lookup array with generations, like the arena in the previous chapter.

Rust does not change how archetypes work. What it changes is that a query hands out &mut Position and &Velocity references, and the library must prove they never alias. Libraries do that with the same runtime check we used, done once per query, plus a little unsafe inside to hand out the slices.

Using hecs

hecs is a small, library-style archetype ECS: a World and queries, no scheduler and no framework. It is the closest thing to EnTT in spirit:

use hecs::World;

struct Position(f32, f32);
struct Velocity(f32, f32);
struct Frozen;

let mut world = World::new();
let ship = world.spawn((Position(0.0, 0.0), Velocity(10.0, 0.0)));
world.spawn((Position(1.0, 1.0), Velocity(0.0, 1.0), Frozen));

// Iterate entities that have Position and Velocity, but not Frozen.
for (_entity, (p, v)) in world
    .query_mut::<(&mut Position, &Velocity)>()
    .without::<&Frozen>()
{
    p.0 += v.0 * 0.016;
    p.1 += v.1 * 0.016;
}

world.insert_one(ship, Frozen)?;     // moves the entity to another archetype
world.despawn(ship)?;                // the old Entity is now stale: get() returns Err

query_mut takes &mut World, so the compiler alone proves exclusivity. The shared version, world.query::<...>() on &World, checks column borrows at run time, like our RefCells.

Using bevy_ecs

bevy_ecs is the ECS of the Bevy engine, and works as a standalone crate. Systems are ordinary functions whose parameter types describe their data access. The scheduler reads those types and runs systems whose access does not conflict on different threads:

use bevy_ecs::prelude::*;

#[derive(Component)] struct Position(f32, f32);
#[derive(Component)] struct Velocity(f32, f32);
#[derive(Component)] struct Health(i32);
#[derive(Resource)]  struct Time { dt: f32 }

fn movement(time: Res<Time>, mut q: Query<(&mut Position, &Velocity)>) {
    for (mut p, v) in &mut q {
        p.0 += v.0 * time.dt;
        p.1 += v.1 * time.dt;
    }
}

fn regenerate(mut q: Query<&mut Health>) {
    for mut h in &mut q {
        h.0 = (h.0 + 1).min(100);
    }
}

let mut world = World::new();
world.insert_resource(Time { dt: 1.0 / 60.0 });
world.spawn((Position(0.0, 0.0), Velocity(1.0, 0.0), Health(50)));

let mut schedule = Schedule::default();
schedule.add_systems((movement, regenerate));  // disjoint access: may run in parallel
schedule.run(&mut world);

movement writes Position and reads Velocity and Time; regenerate writes Health. No overlap, so the scheduler may run them at the same time. If two systems both wrote Position, it would run them one after the other. A single system that asks for Query<&mut Position> twice is rejected when the schedule is built.

Res<Time> is a resource: a singleton stored in the world. This is how ECS code handles global state without static mut, a topic the game loop chapter returns to.

Parallel systems, by hand

The scheduler is not magic. Split borrows plus scoped threads give you the same thing for the struct-of-arrays world, and the compiler checks it:

#[derive(Default)]
struct World {
    pos: Vec<[f32; 2]>,
    vel: Vec<[f32; 2]>,
    health: Vec<i32>,
}

fn main() {
    let mut w = World {
        pos: vec![[0.0, 0.0]; 4],
        vel: vec![[1.0, 2.0]; 4],
        health: vec![10; 4],
    };

    // Destructure into disjoint borrows, then hand them to different threads.
    let World { pos, vel, health } = &mut w;
    std::thread::scope(|s| {
        s.spawn(|| {
            for (p, v) in pos.iter_mut().zip(vel.iter()) {
                p[0] += v[0];
                p[1] += v[1];
            }
        });
        s.spawn(|| {
            for h in health.iter_mut() {
                *h -= 1;
            }
        });
    });
    println!("{:?} {:?}", w.pos[0], w.health);
}

If both threads tried to write pos, the program would not compile. In C++, the same mistake compiles and becomes a data race you look for in a frame capture. Here the scheduler's job, deciding what can run together, is done by the type checker.

Hierarchies in an ECS

Scene graphs do not disappear; they become data. Parent links are components holding entity IDs, and the world transform is computed by a system:

#[derive(Clone, Copy)]
struct Parent(usize);

fn propagate(parents: &[Option<Parent>], local: &[f32], world: &mut [f32]) {
    // Assumes parents come before children (sort once when the hierarchy changes).
    for e in 0..local.len() {
        world[e] = match parents[e] {
            Some(Parent(p)) => world[p] + local[e],
            None => local[e],
        };
    }
}

fn main() {
    let parents = [None, Some(Parent(0)), Some(Parent(1))];  // root, arm, hand
    let local = [1.0, 2.0, 0.5];
    let mut world = [0.0; 3];
    propagate(&parents, &local, &mut world);
    println!("{world:?}");
}

No Rc, no RefCell, no Weak: the parent link is an index, the borrows are three plain slices, and the update is a linear pass over contiguous memory. Compare it with the Rc<RefCell<Node>> version at the top of the chapter.

Summary

C++Rust
GameObject* graph, components with owner pointersEntities as IDs, components in columns or archetype tables
std::shared_ptr + weak_ptr scene graphParent(Entity) component and a propagation system
EnTT, flecshecs (library), bevy_ecs (with scheduler)
Hand-written job graph with read/write declarationsSystem parameter types (Query<&mut T>, Res<T>)
Data races found in capturesConflicting access rejected by the compiler or at schedule build
void* + type IDBox<dyn Any> + downcast_ref

Exercises

  1. Add generational entity IDs and a despawn to the generic World, reusing the Handle idea from Handles and arenas. What should insert do with a stale entity?
  2. In the generic World, write a system that calls world.write::<Position>() twice in the same scope. Run it. Which error do you get, and when would the compiler have caught it instead?
  3. Add a third thread to the parallel example that reads pos while the first writes it. Read the compiler error, then fix it by running the reader after the scope ends.

Math libraries and SIMD

Every engine has a vector math library, and in C++ it is usually GLM, DirectXMath, Eigen or something written in-house. Rust has a few mature ones, and they look familiar: small Copy structs with overloaded operators. This chapter shows how to use them, how to lay out math types for the GPU, and how to go from auto-vectorized loops down to explicit SIMD intrinsics.

This chapter covers:

  • glam and nalgebra, and how they compare with GLM and Eigen,
  • #[repr(C)] math types and bytemuck for GPU uploads,
  • checking auto-vectorization,
  • core::arch intrinsics and runtime CPU feature detection,
  • portable SIMD (std::simd) and the stable alternatives.

Choosing a math library

CrateLikeNotes
glamGLM, DirectXMathVec3, Vec4, Mat4, Quat for f32 (and f64/integer variants). SIMD inside on x86 and ARM. Used by Bevy and most Rust renderers.
nalgebraEigenGeneric over scalar type and dimension, including dynamic matrices, decompositions. Used by physics (Rapier).
ultravioletISPC-style math"Wide" types (Vec3x8) that process 8 vectors at once, SoA style.
mint(interop)Plain #[repr(C)] types that other math crates convert to and from, so libraries can agree on an exchange type.

For a game or renderer, start with glam. It is small, fast and graphics-oriented (right-handed and left-handed projection helpers, quaternions, affine transforms):

use glam::{Mat4, Quat, Vec3};

let model = Mat4::from_scale_rotation_translation(
    Vec3::splat(2.0),
    Quat::from_rotation_y(std::f32::consts::FRAC_PI_4),
    Vec3::new(0.0, 1.0, -5.0),
);
let view = Mat4::look_at_rh(Vec3::new(0.0, 2.0, 5.0), Vec3::ZERO, Vec3::Y);
let proj = Mat4::perspective_rh(60f32.to_radians(), 16.0 / 9.0, 0.1, 100.0);
let mvp = proj * view * model;                 // operator overloading, as in GLM
let clip = mvp * Vec3::new(1.0, 0.0, 0.0).extend(1.0);
let n = (Vec3::X + Vec3::Y).normalize();
let d = n.dot(Vec3::Z);

Two differences from GLM matter in practice:

  • No implicit conversions. There is no vec4(v3, 1.0) constructor overload that silently picks a meaning; you write v3.extend(1.0) or Vec4::from((v3, 1.0)). f32 to f64 is never implicit either.
  • Projection conventions are explicit in the name: perspective_rh produces a 0-to-1 depth range (Vulkan, D3D, WebGPU), perspective_rh_gl produces -1-to-1 (OpenGL). GLM picks one with a #define.

What a vector type looks like

You will often write a few small math types yourself (in shaders' uniform structs, in a physics prototype). Here is a minimal Vec3, with the operator traits from Operators and conversions:

use std::ops::{Add, Mul, Neg, Sub};

#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[repr(C)]
pub struct Vec3 { pub x: f32, pub y: f32, pub z: f32 }

impl Vec3 {
    pub const fn new(x: f32, y: f32, z: f32) -> Self { Vec3 { x, y, z } }
    pub fn dot(self, o: Self) -> f32 { self.x * o.x + self.y * o.y + self.z * o.z }
    pub fn cross(self, o: Self) -> Self {
        Vec3::new(self.y * o.z - self.z * o.y, self.z * o.x - self.x * o.z, self.x * o.y - self.y * o.x)
    }
    pub fn length(self) -> f32 { self.dot(self).sqrt() }
    pub fn normalize_or_zero(self) -> Self {
        let len = self.length();
        if len > 0.0 { self * (1.0 / len) } else { Vec3::default() }
    }
}

impl Add for Vec3 { type Output = Vec3; fn add(self, o: Vec3) -> Vec3 { Vec3::new(self.x + o.x, self.y + o.y, self.z + o.z) } }
impl Sub for Vec3 { type Output = Vec3; fn sub(self, o: Vec3) -> Vec3 { Vec3::new(self.x - o.x, self.y - o.y, self.z - o.z) } }
impl Mul<f32> for Vec3 { type Output = Vec3; fn mul(self, s: f32) -> Vec3 { Vec3::new(self.x * s, self.y * s, self.z * s) } }
impl Mul<Vec3> for f32 { type Output = Vec3; fn mul(self, v: Vec3) -> Vec3 { v * self } }
impl Neg for Vec3 { type Output = Vec3; fn neg(self) -> Vec3 { Vec3::new(-self.x, -self.y, -self.z) } }

fn main() {
    let a = Vec3::new(1.0, 0.0, 0.0);
    let b = Vec3::new(0.0, 1.0, 0.0);
    let n = a.cross(b);
    println!("{n:?} {} {:?}", n.length(), (2.0 * a - b).normalize_or_zero());
}

The types are Copy and passed by value. For 12 or 16 bytes that is what you want: they travel in registers, and there is no const Vec3& to write.

Laying out data for the GPU

Uniform and vertex buffers are bytes with a layout the shader expects. In C++ you memcpy a struct and hope the padding matches. In Rust, the bytemuck crate lets you turn a struct or slice into &[u8] without unsafe, but only for types that implement Pod ("plain old data": #[repr(C)], no padding, no pointers, every bit pattern valid). #[derive(Pod)] checks those conditions at compile time:

use bytemuck::{Pod, Zeroable};

#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct Vertex {
    position: [f32; 3],
    normal: [f32; 3],
    uv: [f32; 2],
}

#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct CameraUniform {
    view_proj: [[f32; 4]; 4],
    eye: [f32; 3],
    _pad: f32,              // std140: vec3 occupies 16 bytes. Without this field,
}                           // derive(Pod) fails: the struct would have tail padding.

let vertices: Vec<Vertex> = load_mesh();
let bytes: &[u8] = bytemuck::cast_slice(&vertices);   // zero-copy, safe
queue.write_buffer(&vertex_buffer, 0, bytes);

If you forget _pad, the #[derive(Pod)] fails to compile because the struct has padding bytes (reading them would be reading uninitialized memory). This turns a class of "my uniform is shifted by 4 bytes" bugs into compile errors. For checking that a Rust struct matches a WGSL or GLSL layout exactly, the encase and crevice crates generate std140/std430 layouts for you.

You can add your own static checks with const assertions, the Rust static_assert:

#[repr(C)]
#[derive(Clone, Copy)]
struct Light {
    position: [f32; 3],
    radius: f32,
    color: [f32; 3],
    intensity: f32,
}

const _: () = assert!(std::mem::size_of::<Light>() == 32);
const _: () = assert!(std::mem::offset_of!(Light, color) == 16);

fn main() {
    println!("Light is {} bytes", std::mem::size_of::<Light>());
}

Auto-vectorization

Before writing intrinsics, check what the compiler already does. LLVM vectorizes loops over slices well when it can prove there is no aliasing and no out-of-bounds access, and Rust gives it both more often than C++ does (&mut slices are noalias; iterators have no bounds checks):

pub fn saxpy(a: f32, x: &[f32], y: &mut [f32]) {
    for (yi, xi) in y.iter_mut().zip(x) {
        *yi += a * xi;
    }
}

pub fn sum(values: &[f32]) -> f32 {
    // Floating-point addition is not associative, so LLVM will not reorder a
    // plain `.sum()` into SIMD lanes. Accumulating into 8 lanes yourself lets it.
    let mut acc = [0.0f32; 8];
    let chunks = values.chunks_exact(8);
    let tail: f32 = chunks.remainder().iter().sum();
    for c in chunks {
        for i in 0..8 {
            acc[i] += c[i];
        }
    }
    acc.iter().sum::<f32>() + tail
}

fn main() {
    let x = vec![1.0f32; 1003];
    let mut y = vec![2.0f32; 1003];
    saxpy(3.0, &x, &mut y);
    println!("{} {}", y[0], sum(&y));
}

To see whether a loop vectorized:

  • Open the example in the Playground, choose Release, then Show Assembly, and look for packed instructions (mulps, addps, vfmadd...ps on x86; fmla v0.4s on ARM).
  • Locally, cargo asm --release mycrate::saxpy (from cargo-show-asm), or Compiler Explorer with -C opt-level=3.
  • Enable wider instructions with -C target-cpu=native or -C target-feature=+avx2,+fma in .cargo/config.toml. Without it, x86-64 code only assumes SSE2, exactly like a default C++ compiler.

chunks_exact(8) is the idiom that makes the trip count a multiple of the vector width: inside the loop, c is known to have length 8, so the inner c[i] needs no bounds check.

Intrinsics: core::arch

When you need a specific instruction, the intrinsics are in std::arch (alias core::arch), under the same names as in Intel's and ARM's headers: _mm_add_ps, _mm256_fmadd_ps, vaddq_f32. They are unsafe because calling an AVX2 instruction on a CPU without AVX2 is undefined behavior.

The safe pattern has three parts: a function compiled for the feature with #[target_feature], a runtime check with is_x86_feature_detected!, and a scalar fallback.

#[cfg(target_arch = "x86_64")]
mod simd {
    use std::arch::x86_64::*;

    /// out[i] = a[i] + b[i], 8 lanes at a time, using AVX.
    #[target_feature(enable = "avx")]
    pub fn add_arrays_avx(a: &[f32], b: &[f32], out: &mut [f32]) {
        assert!(a.len() == b.len() && b.len() == out.len());
        let n = a.len() / 8 * 8;
        for i in (0..n).step_by(8) {
            // SAFETY: i + 8 <= n <= len for all three slices (checked above),
            // and loadu/storeu have no alignment requirement.
            unsafe {
                let va = _mm256_loadu_ps(a.as_ptr().add(i));
                let vb = _mm256_loadu_ps(b.as_ptr().add(i));
                _mm256_storeu_ps(out.as_mut_ptr().add(i), _mm256_add_ps(va, vb));
            }
        }
        for i in n..a.len() {
            out[i] = a[i] + b[i];
        }
    }
}

fn add_arrays(a: &[f32], b: &[f32], out: &mut [f32]) {
    #[cfg(target_arch = "x86_64")]
    if is_x86_feature_detected!("avx") {
        // SAFETY: we just checked that the CPU supports AVX.
        return unsafe { simd::add_arrays_avx(a, b, out) };
    }
    for ((o, x), y) in out.iter_mut().zip(a).zip(b) {
        *o = x + y;
    }
}

fn main() {
    let a: Vec<f32> = (0..20).map(|i| i as f32).collect();
    let b = vec![0.5f32; 20];
    let mut out = vec![0.0f32; 20];
    add_arrays(&a, &b, &mut out);
    println!("{:?}", &out[..10]);
}

Notes for C++ intrinsics users:

  • #[target_feature(enable = "avx")] is __attribute__((target("avx"))). Calling such a function is unsafe from code not compiled with that feature, which is what forces the runtime check.
  • is_x86_feature_detected! caches the CPUID result; the check costs a load and a branch. On ARM, use std::arch::is_aarch64_feature_detected!. NEON is always present on AArch64, so most NEON code needs no check.
  • Inside a #[target_feature] function, intrinsics that do not touch memory (_mm256_add_ps) are safe to call in recent Rust. Loads and stores through raw pointers still need unsafe, with a SAFETY comment.
  • To compile everything for a known baseline instead, set -C target-cpu=x86-64-v3 (AVX2, FMA) and drop the runtime checks.

Portable SIMD

std::simd provides f32x4, f32x8, u8x16 and friends with operators and lane-wise methods, compiled to whatever the target supports. It is the Rust equivalent of std::experimental::simd and, like it, is not yet stable: it requires a nightly compiler.

#![feature(portable_simd)]
use std::simd::prelude::*;

fn sum(values: &[f32]) -> f32 {
    let (head, body, tail) = values.as_simd::<8>();   // aligned middle part
    let mut acc = f32x8::splat(0.0);
    for v in body {
        acc += *v;
    }
    acc.reduce_sum() + head.iter().sum::<f32>() + tail.iter().sum::<f32>()
}

On stable Rust, the wide crate offers similar types (f32x8) today, and glam already uses SIMD internally for Vec4, Mat4 and Quat. For most engine code, the order of preference is:

  1. Write slice loops the compiler can vectorize, and check the assembly.
  2. Use SIMD-backed types from a library (glam, wide, ultraviolet).
  3. Write core::arch intrinsics in a small module with runtime detection and SAFETY comments.

Floating-point behavior

Rust follows IEEE 754 by default and never enables fast-math globally: no reassociation, no flush-to-zero, NaNs and infinities preserved. Some things to know:

  • f32::mul_add is a fused multiply-add (one rounding). It compiles to an FMA instruction when the target has one, and to a slow software routine when it does not, so enable +fma if you use it in hot code.
  • f32::min and f32::max ignore NaN (they return the other operand), unlike std::min which depends on argument order. clamp panics if min > max.
  • total_cmp gives a total order (for sorting floats); f32 does not implement Ord, so sort() on a Vec<f32> does not compile. Use v.sort_by(f32::total_cmp).
  • Float to integer casts with as saturate: 300.7f32 as u8 == 255, f32::NAN as i32 == 0. In C++, out-of-range conversion is undefined behavior.
fn main() {
    let mut depths = vec![3.5f32, -1.0, f32::NAN, 0.25];
    depths.sort_by(f32::total_cmp);
    println!("{depths:?}");
    println!("{} {} {}", 300.7f32 as u8, f32::NAN as i32, (-5.0f32) as u32);
    println!("{}", f32::NAN.max(1.0));
}

Summary

C++Rust
GLM, DirectXMathglam
Eigennalgebra
memcpy struct into a bufferbytemuck::cast_slice on #[derive(Pod)] types
static_assert(sizeof(T) == 32)const _: () = assert!(size_of::<T>() == 32);
<immintrin.h>, <arm_neon.h>std::arch::x86_64, std::arch::aarch64
__attribute__((target("avx2")))#[target_feature(enable = "avx2")]
__builtin_cpu_supportsis_x86_feature_detected!
std::experimental::simdstd::simd (nightly), wide (stable)
-march=native-C target-cpu=native
UB on out-of-range float → intSaturating as casts

Exercises

  1. Add Mul<Vec3> for Vec3 (component-wise) and a lerp method to the Vec3 example. Check the Playground assembly for lerp in release mode.
  2. Remove _pad from a #[derive(Pod)] struct in a local project with bytemuck. Read the error. Then write a const assertion that catches the same mistake without bytemuck.
  3. Write an SSE2 version of add_arrays with _mm_add_ps (4 lanes). SSE2 is part of the x86-64 baseline: does it need runtime detection?

OpenGL from Rust

OpenGL is a C API built on a hidden global: the current context, plus a large state machine of bindings. That makes it the least Rust-shaped graphics API, and therefore a good place to see how Rust code wraps a C API it cannot change. If you have written GL against GLFW and a loader such as glad, everything here will look familiar; the new parts are where ownership and Drop replace manual glDelete* calls.

This chapter covers:

  • getting a window and a context with winit and glutin,
  • loading GL functions with the gl and glow crates,
  • buffers, shaders and uploads with bytemuck,
  • wrapping GL object names in types with Drop,
  • what the borrow checker can and cannot do for a state machine.

The crates

JobC/C++Rust
Window and eventsGLFW, SDLwinit (or the sdl2/glfw bindings)
Context creationGLFW, SDL, WGL/GLX/EGLglutin (with glutin-winit)
Function loaderglad, GLEWgl (generated, C-style) or glow (thin wrapper, also runs on WebGL)
Casting structs to bytesreinterpret_cast, memcpybytemuck

The gl crate is a generated binding with exactly the C names: you call gl::GenBuffers(1, &mut id) inside unsafe, and porting C++ code is mostly mechanical. glow ("GL on whatever") wraps the same calls in slightly more Rust-like signatures (returning the new object, taking slices instead of pointer + length) and runs on desktop GL, GLES and WebGL2 in the browser. Both leave every call unsafe, because the driver can do anything with a bad argument. This chapter uses glow.

Window, context and loader

Creating a context is the most boilerplate-heavy part, as it is in C++ without GLFW. With winit 0.30 and glutin 0.32, the outline is:

use glutin::prelude::*;
use glutin_winit::DisplayBuilder;
use winit::event_loop::EventLoop;

let event_loop = EventLoop::new()?;
let window_attrs = winit::window::Window::default_attributes().with_title("GL");
let template = glutin::config::ConfigTemplateBuilder::new().with_alpha_size(8);

// Pick a framebuffer config and create the window together (needed on some platforms).
let (window, gl_config) = DisplayBuilder::new()
    .with_window_attributes(Some(window_attrs))
    .build(&event_loop, template, |mut configs| configs.next().unwrap())?;
let window = window.unwrap();
let display = gl_config.display();

let context_attrs = glutin::context::ContextAttributesBuilder::new()
    .with_context_api(glutin::context::ContextApi::OpenGl(Some(glutin::context::Version::new(4, 1))))
    .build(Some(window_handle(&window)));
let surface_attrs = window.build_surface_attributes(Default::default())?;
let surface = unsafe { display.create_window_surface(&gl_config, &surface_attrs)? };
let context = unsafe { display.create_context(&gl_config, &context_attrs)? }
    .make_current(&surface)?;

// The loader: the equivalent of gladLoadGLLoader(glfwGetProcAddress).
let gl = unsafe {
    glow::Context::from_loader_function_cstr(|name| display.get_proc_address(name))
};

The glutin repository has a complete, maintained example; copy it rather than writing this from memory. The game loop chapter covers the winit event loop that drives rendering.

Notice the types: make_current consumes a NotCurrentContext and returns a PossiblyCurrentContext. The "is this context current?" state that GL keeps globally is partly moved into the type system, so you cannot make a context current twice by accident.

A triangle

With a glow::Context in hand, the GL calls are the ones you know:

use glow::HasContext;

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Vertex { pos: [f32; 2], color: [f32; 3] }

const VERTICES: [Vertex; 3] = [
    Vertex { pos: [-0.5, -0.5], color: [1.0, 0.0, 0.0] },
    Vertex { pos: [ 0.5, -0.5], color: [0.0, 1.0, 0.0] },
    Vertex { pos: [ 0.0,  0.5], color: [0.0, 0.0, 1.0] },
];

unsafe {
    let vao = gl.create_vertex_array()?;          // Result<NativeVertexArray, String>
    gl.bind_vertex_array(Some(vao));

    let vbo = gl.create_buffer()?;
    gl.bind_buffer(glow::ARRAY_BUFFER, Some(vbo));
    gl.buffer_data_u8_slice(glow::ARRAY_BUFFER, bytemuck::cast_slice(&VERTICES), glow::STATIC_DRAW);

    let stride = std::mem::size_of::<Vertex>() as i32;
    gl.enable_vertex_attrib_array(0);
    gl.vertex_attrib_pointer_f32(0, 2, glow::FLOAT, false, stride, std::mem::offset_of!(Vertex, pos) as i32);
    gl.enable_vertex_attrib_array(1);
    gl.vertex_attrib_pointer_f32(1, 3, glow::FLOAT, false, stride, std::mem::offset_of!(Vertex, color) as i32);

    let program = link_program(&gl, VERTEX_SRC, FRAGMENT_SRC)?;

    // Each frame:
    gl.clear_color(0.1, 0.1, 0.12, 1.0);
    gl.clear(glow::COLOR_BUFFER_BIT);
    gl.use_program(Some(program));
    gl.draw_arrays(glow::TRIANGLES, 0, 3);
}
surface.swap_buffers(&context)?;

Compared with C++:

  • bytemuck::cast_slice(&VERTICES) replaces sizeof(vertices), vertices. The byte length comes from the slice, so the size argument cannot be wrong, and Pod guarantees the struct has no padding.
  • offset_of!(Vertex, pos) replaces (void*)offsetof(Vertex, pos).
  • Object names are typed (NativeBuffer, NativeProgram), not bare GLuint, so passing a buffer where a texture is expected does not compile.
  • Some(vbo) / None replaces "0 means unbind".

Shader compilation returns the info log as a String in the error case:

unsafe fn compile(gl: &glow::Context, kind: u32, src: &str) -> Result<glow::NativeShader, String> {
    unsafe {
        let shader = gl.create_shader(kind)?;
        gl.shader_source(shader, src);
        gl.compile_shader(shader);
        if gl.get_shader_compile_status(shader) {
            Ok(shader)
        } else {
            let log = gl.get_shader_info_log(shader);
            gl.delete_shader(shader);
            Err(log)
        }
    }
}

With ?, a shader error propagates up to whoever can report it, and the delete_shader on the error path is hard to forget because the function has exactly two exits. But it is still manual. The next section makes cleanup automatic.

Owning GL objects with Drop

A GL object name is a resource like a file handle: it must be deleted exactly once, and not used afterwards. That is the definition of an owned type with a Drop impl. The one complication is that deleting needs the context, so the wrapper keeps a reference-counted handle to it.

The example below uses a small fake Gl that prints the calls it receives, so it runs on the Playground. With glow, the bodies would be unsafe { self.gl.delete_buffer(self.id) } and so on.

use std::cell::Cell;
use std::marker::PhantomData;
use std::rc::Rc;

// Stand-in for glow::Context: hands out names and logs calls.
#[derive(Default)]
pub struct Gl { next: Cell<u32> }
impl Gl {
    fn gen_buffer(&self) -> u32 { self.next.set(self.next.get() + 1); println!("glGenBuffers -> {}", self.next.get()); self.next.get() }
    fn buffer_data(&self, id: u32, size: usize) { println!("glBufferData({id}, {size} bytes)"); }
    fn delete_buffer(&self, id: u32) { println!("glDeleteBuffers({id})"); }
}

/// A GPU buffer holding elements of type T. Deleted when dropped.
pub struct Buffer<T> {
    gl: Rc<Gl>,          // keeps the context alive; also makes Buffer !Send
    id: u32,
    len: usize,
    _marker: PhantomData<T>,
}

impl<T: Copy> Buffer<T> {
    pub fn new(gl: &Rc<Gl>, data: &[T]) -> Self {
        let id = gl.gen_buffer();
        // With glow and bytemuck: gl.buffer_data_u8_slice(target, bytemuck::cast_slice(data), usage),
        // with the bound T: Pod. The fake only needs the byte count.
        gl.buffer_data(id, std::mem::size_of_val(data));
        Buffer { gl: gl.clone(), id, len: data.len(), _marker: PhantomData }
    }
    pub fn len(&self) -> usize { self.len }
}

impl<T> Drop for Buffer<T> {
    fn drop(&mut self) {
        self.gl.delete_buffer(self.id);
    }
}

struct Mesh {
    vertices: Buffer<[f32; 3]>,
    indices: Buffer<u16>,
}

fn main() {
    let gl = Rc::new(Gl::default());
    {
        let mesh = Mesh {
            vertices: Buffer::new(&gl, &[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]),
            indices: Buffer::new(&gl, &[0, 1, 2]),
        };
        println!("drawing {} indices", mesh.indices.len());
        let _ = mesh.vertices.len();
    } // mesh dropped here: both buffers deleted, in field declaration order
    println!("end of scope");
}

This is RAII exactly as in a C++ wrapper class, with three differences that remove the usual pitfalls:

  • No rule of five. In C++ a GlBuffer class must delete its copy constructor and write a move constructor that zeroes the source, or a copy will double-delete. A Rust struct without Clone cannot be copied, and a move leaves nothing behind to drop. The wrapper above is complete.
  • Typed buffers. Buffer<u16> and Buffer<[f32; 3]> are different types, so passing the vertex buffer where the index buffer is expected is a compile error, and len() counts elements, not bytes.
  • Thread affinity is checked. A GL context is current on one thread. The Rc inside makes Buffer neither Send nor Sync, so the compiler rejects moving it to a worker thread. In C++, that bug shows up as a driver crash or a silent no-op.
Engine note

Many engines do not delete GL objects from Drop directly, because a drop can happen while the object is still referenced by queued draw calls, or from a thread without the context. The common alternative is a deletion queue: Drop pushes the name onto a list owned by the renderer, and the renderer deletes everything in the list at a safe point in the frame. The ownership logic is the same; only the timing changes. Vulkan needs this from the start.

The bind-to-edit state machine

GL's global bindings are the part Rust can do least about. glBindBuffer changes hidden state that later calls depend on, and nothing in the types records it. Options, from least to most structure:

  1. Use DSA (direct state access, GL 4.5). glNamedBufferData(id, ...) takes the object directly, and most of the hidden state disappears. glow exposes these as named_buffer_data_u8_slice and friends. If you can require GL 4.5, do this.
  2. Re-bind before every use. Simple, and the driver ignores redundant binds cheaply on most implementations.
  3. Guards. A method buffer.bind(&mut gl_state) -> BoundBuffer<'_> that borrows a state object mutably. Only one buffer can be bound at a time because only one &mut borrow of the state can exist. This encodes the state machine in lifetimes, but it is usually more ceremony than it is worth for GL.

In practice, wrap object lifetime (which Drop handles completely) and keep the binding calls explicit. Lifetime bugs are the expensive ones.

Debugging

Your tools still work: RenderDoc, Nsight and apitrace capture GL calls from a Rust program the same way. Enable KHR_debug output with gl.debug_message_callback(...) and route messages into your logger (log/tracing), as you would with glDebugMessageCallback.

Summary

C++Rust
GLFW / SDL windowwinit
GLFW / WGL / GLX / EGL contextglutin
glad / GLEWgl (C names) or glow (typed, also WebGL)
GLuint namesglow::NativeBuffer, NativeTexture, ...
sizeof(v), v.data()bytemuck::cast_slice(&v)
offsetofstd::mem::offset_of!
RAII wrapper with deleted copy and hand-written moveStruct + Drop; no Clone means no copies
"Only call from the GL thread" commentRc inside: !Send, enforced by the compiler

Exercises

  1. Add a Texture wrapper to the fake-Gl example, and a Material that owns a Texture and a Buffer<f32>. Predict the deletion order when a Material is dropped, then run it.
  2. Try to send a Buffer to another thread with std::thread::spawn. Read the error and find where it mentions Rc.
  3. Change Drop for Buffer to push the name into a RefCell<Vec<u32>> deletion queue in Gl, and add a Gl::collect_garbage that deletes them. Call it at the "end of the frame".

Vulkan with ash

Vulkan was designed to be explicit: you create every object, you synchronize every access, and you destroy everything in the right order. That makes it a natural fit for Rust's ownership model, and also the place where you feel most clearly what Rust can check and what it cannot. This chapter uses ash, the most widely used Vulkan binding, which is a thin, unsafe, one-to-one mapping of the C API.

This chapter covers:

  • what ash is, and how it maps to vulkan.h,
  • create-info structs, p_next chains, and how lifetimes check them,
  • designing safe wrappers: what to make safe and what to leave unsafe,
  • resource lifetime with frames in flight, and deletion queues,
  • the higher-level alternatives (vulkano, wgpu).

ash in one page

ash is generated from vk.xml, the same registry that produces vulkan.h. Every function and struct is there, under predictable names:

Cash
VkBufferCreateInfovk::BufferCreateInfo
VK_BUFFER_USAGE_VERTEX_BUFFER_BITvk::BufferUsageFlags::VERTEX_BUFFER
VK_FORMAT_R8G8B8A8_SRGBvk::Format::R8G8B8A8_SRGB
vkCreateBuffer(device, &info, NULL, &buf)device.create_buffer(&info, None) returns VkResult<vk::Buffer>
vkCmdDraw(cmd, 3, 1, 0, 0)device.cmd_draw(cmd, 3, 1, 0, 0)
vkGetDeviceProcAddr tablesash::Device holds the loaded function pointers
Extension functionsash::khr::swapchain::Device::new(&instance, &device)

Almost every call is unsafe, because the Vulkan spec lists "valid usage" rules that a binding cannot check: a buffer must not be destroyed while a command buffer that uses it is pending, an image must be in the right layout, and so on. ash's job is to make the calls convenient and typed; correctness is still on you, plus the validation layers.

A minimal instance:

use ash::vk;

let entry = unsafe { ash::Entry::load()? };          // loads libvulkan / vulkan-1.dll

let app_info = vk::ApplicationInfo::default()
    .application_name(c"my-engine")
    .api_version(vk::API_VERSION_1_3);

let layers = [c"VK_LAYER_KHRONOS_validation".as_ptr()];
let create_info = vk::InstanceCreateInfo::default()
    .application_info(&app_info)
    .enabled_layer_names(&layers);

let instance = unsafe { entry.create_instance(&create_info, None)? };
// ... later, after everything created from it is destroyed:
unsafe { instance.destroy_instance(None) };

Compared with C:

  • vk::...::default() fills in sType and zeroes the rest. You never write VK_STRUCTURE_TYPE_... by hand.
  • Builder methods take slices and set both the pointer and the count: .enabled_layer_names(&layers) sets ppEnabledLayerNames and enabledLayerCount together, so they cannot disagree.
  • Errors come back as Result<T, vk::Result>, so ? propagates VK_ERROR_OUT_OF_DEVICE_MEMORY instead of an if (res != VK_SUCCESS) after every call.
  • c"..." is a C string literal (&CStr, null-terminated), the type Vulkan wants for names.

Lifetimes on create-info structs

The classic C bug with create-info structs is a dangling pointer: you point pQueueFamilyIndices at a temporary array, the array dies, and the call reads garbage. ash's builder structs carry a lifetime parameter, vk::BufferCreateInfo<'a>, which records "this struct borrows something for 'a". The compiler then rejects the dangling version.

Here is the same idea in a few lines you can run, with a stand-in for an ash struct:

use std::marker::PhantomData;

// Like ash's vk::BufferCreateInfo<'a>: raw pointers inside, a lifetime outside.
#[derive(Default)]
struct BufferCreateInfo<'a> {
    size: u64,
    queue_family_index_count: u32,
    p_queue_family_indices: *const u32,
    _marker: PhantomData<&'a ()>,
}

impl<'a> BufferCreateInfo<'a> {
    fn size(mut self, size: u64) -> Self { self.size = size; self }
    fn queue_family_indices(mut self, indices: &'a [u32]) -> Self {
        self.queue_family_index_count = indices.len() as u32;
        self.p_queue_family_indices = indices.as_ptr();
        self
    }
}

fn create_buffer(info: &BufferCreateInfo) {
    // A real binding would pass `info` to vkCreateBuffer, which reads the pointer.
    let families = unsafe {
        std::slice::from_raw_parts(info.p_queue_family_indices, info.queue_family_index_count as usize)
    };
    println!("buffer of {} bytes shared by queue families {:?}", info.size, families);
}

fn main() {
    let families = vec![0u32, 2];
    let info = BufferCreateInfo::default().size(4096).queue_family_indices(&families);
    create_buffer(&info);
}

And the bug, which compiles in C and C++:

use std::marker::PhantomData;
#[derive(Default)]
struct BufferCreateInfo<'a> { p: *const u32, n: u32, _m: PhantomData<&'a ()> }
impl<'a> BufferCreateInfo<'a> {
    fn queue_family_indices(mut self, i: &'a [u32]) -> Self { self.p = i.as_ptr(); self.n = i.len() as u32; self }
}
fn create_buffer(_: &BufferCreateInfo) {}
fn main() {
    let info = {
        let families = vec![0u32, 2];
        BufferCreateInfo::default().queue_family_indices(&families)
    };                       // error[E0597]: `families` does not live long enough
    create_buffer(&info);
}

The same mechanism checks p_next chains. In ash, push_next takes &'a mut T where T must implement the marker trait for that chain (for example ExtendsPhysicalDeviceFeatures2), so you can only chain structs the spec allows, and they must outlive the struct they extend:

let mut features13 = vk::PhysicalDeviceVulkan13Features::default()
    .dynamic_rendering(true)
    .synchronization2(true);
let mut features12 = vk::PhysicalDeviceVulkan12Features::default()
    .buffer_device_address(true)
    .descriptor_indexing(true);

let queue_info = [vk::DeviceQueueCreateInfo::default()
    .queue_family_index(graphics_family)
    .queue_priorities(&[1.0])];
let extensions = [ash::khr::swapchain::NAME.as_ptr()];

let device_info = vk::DeviceCreateInfo::default()
    .queue_create_infos(&queue_info)
    .enabled_extension_names(&extensions)
    .push_next(&mut features13)        // checked: PhysicalDeviceVulkan13Features extends DeviceCreateInfo
    .push_next(&mut features12);

let device = unsafe { instance.create_device(physical_device, &device_info, None)? };

Lifetimes check memory validity, which is exactly the part of Vulkan usage that is a C problem rather than a GPU problem. They do not check GPU validity rules; the validation layers still do that.

What to make safe

A safe Vulkan wrapper that rules out every misuse is a large project (vulkano is one, and it pays for it with runtime tracking). An engine usually takes a middle path. Here is a reasonable split:

ConcernMake it safe withLeave unsafe / validated by layers
Object destroyed exactly onceDrop on owning wrappers
Children destroyed before parent (buffer before device)Child holds an Arc of the device
Create-info pointer validityash lifetimes
Freed while the GPU still uses itDeletion queue keyed by frame
Thread rules (external synchronization)&mut for externally synchronized objects (command pools, queues)
Image layouts, barriersRender graph or careful code + validation
Descriptor contents matching shadersReflection at load timeValidation

The first two rows are the classic C++ "destroy in reverse order" problem, and in Rust they come for free from Arc and Drop:

use std::sync::Arc;

// Stand-ins for ash::Device and vk::Buffer.
struct RawDevice;
#[derive(Clone, Copy, Debug)]
#[allow(dead_code)]
struct RawBuffer(u64);

struct DeviceShared {
    raw: RawDevice,
}
impl Drop for DeviceShared {
    fn drop(&mut self) {
        println!("vkDestroyDevice");   // runs only after every Arc is gone
        let _ = &self.raw;
    }
}

#[derive(Clone)]
pub struct Device(Arc<DeviceShared>);

pub struct Buffer {
    device: Device,      // keeps the device alive as long as this buffer exists
    raw: RawBuffer,
}

impl Device {
    pub fn new() -> Device {
        println!("vkCreateDevice");
        Device(Arc::new(DeviceShared { raw: RawDevice }))
    }
    pub fn create_buffer(&self, id: u64) -> Buffer {
        println!("vkCreateBuffer -> {id}");
        Buffer { device: self.clone(), raw: RawBuffer(id) }
    }
}

impl Drop for Buffer {
    fn drop(&mut self) {
        println!("vkDestroyBuffer({:?})", self.raw);
        let _ = &self.device.0.raw;    // a real wrapper calls self.device.raw.destroy_buffer(...)
    }
}

fn main() {
    let device = Device::new();
    let vertex = device.create_buffer(1);
    let index = device.create_buffer(2);
    drop(device);                       // the device is NOT destroyed yet...
    println!("dropped our device handle");
    drop(vertex);
    drop(index);                        // ...it is destroyed after the last buffer
}

The order of destruction is now a property of the data structure, not of the order of lines in a shutdown function. Arc costs an atomic increment per created object, which is nothing compared with vkCreateBuffer.

Frames in flight

The hardest lifetime in Vulkan is not a CPU lifetime at all. When you drop a Buffer on the CPU, the GPU may still be executing a command buffer, recorded one or two frames ago, that reads it. Destroying it immediately is a use-after-free on the GPU, and Drop alone cannot know.

The standard solution, in C++ and in Rust, is a deletion queue: dropping a resource defers its destruction until the frame that last used it has finished on the GPU (its fence has signaled). With N frames in flight, a resource dropped during frame f is safe to destroy when frame f completes, which you know when you wait on that frame's fence at the start of frame f + N:

use std::cell::RefCell;
use std::rc::Rc;

const FRAMES_IN_FLIGHT: u64 = 2;

#[derive(Debug)]
#[allow(dead_code)] // the ids are only printed
enum Garbage { Buffer(u64), Image(u64) }

#[derive(Default)]
struct DeletionQueue {
    pending: Vec<(u64, Garbage)>,   // (frame in which it was dropped, object)
}

impl DeletionQueue {
    /// Call after waiting on the fence of `completed_frame`.
    fn collect(&mut self, completed_frame: u64) {
        self.pending.retain(|(frame, obj)| {
            if *frame <= completed_frame {
                println!("  destroy {obj:?} (dropped in frame {frame})");
                false
            } else {
                true
            }
        });
    }
}

struct Renderer {
    frame: u64,
    garbage: Rc<RefCell<DeletionQueue>>,
}

struct Buffer {
    id: u64,
    renderer_frame: u64,
    garbage: Rc<RefCell<DeletionQueue>>,
}

impl Drop for Buffer {
    fn drop(&mut self) {
        // Not destroyed now: the GPU may still be reading it.
        self.garbage.borrow_mut().pending.push((self.renderer_frame, Garbage::Buffer(self.id)));
    }
}

impl Renderer {
    fn begin_frame(&mut self) {
        self.frame += 1;
        println!("frame {}", self.frame);
        if self.frame > FRAMES_IN_FLIGHT {
            // Here a real renderer waits on the fence of frame (frame - N).
            let completed = self.frame - FRAMES_IN_FLIGHT;
            self.garbage.borrow_mut().collect(completed);
        }
    }
    fn create_buffer(&self, id: u64) -> Buffer {
        Buffer { id, renderer_frame: self.frame, garbage: self.garbage.clone() }
    }
}

fn main() {
    let mut r = Renderer { frame: 0, garbage: Default::default() };
    r.begin_frame();
    let temp = r.create_buffer(7);
    r.garbage.borrow_mut().pending.push((r.frame, Garbage::Image(3)));
    drop(temp);                       // dropped in frame 1
    for _ in 0..3 {
        r.begin_frame();              // destroyed at the start of frame 3
    }
}

The simplification here is that a buffer records the frame in which it was created; a real renderer records the last frame in which it was used, usually by bumping a counter when a command buffer references it. Some engines use a reference count instead: command buffers hold an Arc to every resource they use and drop those references when their fence signals, so the resource's Drop runs at the right time automatically. wgpu does exactly this internally.

Engine note

Command pools and command buffers are "externally synchronized" in Vulkan: only one thread may use them at a time. Map that to &mut: if recording requires &mut CommandBuffer, the compiler guarantees one recorder at a time, and you give each worker thread its own pool. Queues likewise: queue_submit taking &mut Queue (or a Mutex<Queue>) turns a spec rule into a type rule.

Memory allocation

Allocating a VkDeviceMemory per buffer does not scale, so C++ engines use VulkanMemoryAllocator. In Rust the common choices are the gpu-allocator crate (pure Rust, used by many projects, also supports D3D12) and vk-mem (bindings to VMA itself). Both return allocations that you free explicitly, and both fit the owning-wrapper pattern above: the allocation lives in the Buffer wrapper and is freed in its Drop (or its deletion-queue entry).

Shaders

Vulkan takes SPIR-V. Options for producing it from a Rust build:

  • Compile GLSL or HLSL with glslc/dxc from build.rs and embed the result with include_bytes! (Assets and build shows how).
  • Use shaderc (bindings to the same compiler) at build or run time.
  • Use naga, the pure-Rust shader translator from the wgpu project, to convert WGSL or GLSL to SPIR-V.
  • Write shaders in Rust with rust-gpu, an experimental compiler backend that emits SPIR-V.

include_bytes! gives a &[u8; N] with no alignment guarantee, but SPIR-V must be read as u32 words. ash::util::read_spv copies it into a correctly aligned Vec<u32>.

Higher-level options

CrateLevelUse it when
ashRaw Vulkan, unsafeYou want full control and are writing your own abstraction layer
vulkanoSafe Vulkan with runtime trackingYou want Vulkan concepts but checked, and can accept some overhead
wgpuSafe WebGPU-style API over Vulkan, Metal, D3D12, GL, WebGPUYou want portability and safety; next chapter

Many Rust renderers start on wgpu and only drop to ash where they need a feature wgpu does not expose (mesh shaders, ray tracing, specific extensions).

Summary

C++Rust
vulkan.h, volkash (Entry, Instance, Device hold function tables)
sType = VK_STRUCTURE_TYPE_...vk::Struct::default()
Pointer + count fieldsSlice-taking builder methods
if (res != VK_SUCCESS)Result<T, vk::Result> and ?
Dangling pNext / array pointersRejected by the struct's lifetime parameter
Reverse-order shutdown functionArc<Device> in children, Drop
Deletion queueSame pattern; Drop enqueues
VMAgpu-allocator, vk-mem
"Externally synchronized" in the spec&mut or Mutex in the wrapper's API

Exercises

  1. In the Arc<Device> example, add an Image type that also holds a Device. Put a few buffers and images into a Vec<Box<dyn std::any::Any>>, drop the device handle, then remove the elements in a random order. When is vkDestroyDevice printed?
  2. Change the deletion-queue example so that Buffer records the last frame it was used in (add a fn use_in_frame(&self, frame: u64) with a Cell<u64>). Use the buffer in frame 2, drop it in frame 2, and check that it is destroyed at the start of frame 4.
  3. Read the push_next signature in ash's documentation for vk::DeviceCreateInfo. Which trait bound prevents you from chaining a vk::ImageViewUsageCreateInfo onto a device create info?

wgpu: a safe, portable GPU API

wgpu is a Rust implementation of the WebGPU API. On the desktop it runs on Vulkan, Metal, D3D12 or OpenGL; in the browser it runs on WebGPU (or WebGL2). It is the graphics layer under Bevy, the Firefox WebGPU implementation, and many Rust renderers and tools. For a C++ programmer, think of it as a Vulkan-flavored version of bgfx, sokol_gfx or Dawn, with an API designed in Rust so that misuse that is undefined behavior in Vulkan becomes a compile error or a reported validation error.

This chapter covers:

  • the WebGPU object model, compared with Vulkan,
  • the steps from window to triangle,
  • how wgpu uses ownership and borrowing to make GPU lifetimes safe,
  • uniforms, bind groups and bytemuck,
  • WGSL shaders, naga and SPIR-V,
  • running the same code on the web.

The wgpu API changes between major versions (roughly every few months). The code here shows the shape of the API; check the examples for the version you use.

The object model

If you know Vulkan, WebGPU is Vulkan with the hard parts handled for you:

VulkanwgpuDifference
VkInstanceInstance
VkPhysicalDeviceAdapter
VkDevice + VkQueueDevice + QueueOne queue
VkSurfaceKHR + swapchainSurface + surface.configure()No swapchain images to manage
VkBuffer + VkDeviceMemoryBufferMemory allocated for you
VkImage + VkImageViewTexture + TextureView
Descriptor set layout / setBindGroupLayout / BindGroup
VkPipelineRenderPipeline, ComputePipeline
Command pool + bufferCommandEncoder → CommandBuffer
Render pass begin/endRenderPass value, ends when dropped
Barriers, layoutsNone: tracked automatically
Fences for resource lifetimeNone: tracked automatically

The last two rows are the big ones. wgpu tracks how each resource is used in each pass and inserts barriers and layout transitions itself, and it keeps every resource alive until the GPU has finished with it. Those are the two largest sources of bugs in hand-written Vulkan, and they disappear. The cost is some CPU overhead for the tracking, and less control over exactly when barriers happen.

From window to triangle

Setup, in outline (the window comes from winit; see Game loop):

let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default());
let surface = instance.create_surface(window.clone())?;     // window: Arc<winit::window::Window>

let adapter = instance
    .request_adapter(&wgpu::RequestAdapterOptions {
        power_preference: wgpu::PowerPreference::HighPerformance,
        compatible_surface: Some(&surface),
        force_fallback_adapter: false,
    })
    .await?;
let (device, queue) = adapter.request_device(&wgpu::DeviceDescriptor::default()).await?;

let size = window.inner_size();
let config = surface
    .get_default_config(&adapter, size.width, size.height)
    .expect("surface not supported by adapter");
surface.configure(&device, &config);

The request_* functions are async because on the web they are JavaScript promises. On the desktop, run them with pollster::block_on(...), which simply waits.

A pipeline, from a WGSL shader:

let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
    label: Some("triangle"),
    source: wgpu::ShaderSource::Wgsl(include_str!("triangle.wgsl").into()),
});

let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
    label: Some("triangle"),
    layout: None,                                   // derived from the shader
    vertex: wgpu::VertexState {
        module: &shader,
        entry_point: Some("vs_main"),
        buffers: &[],
        compilation_options: Default::default(),
    },
    fragment: Some(wgpu::FragmentState {
        module: &shader,
        entry_point: Some("fs_main"),
        targets: &[Some(config.format.into())],
        compilation_options: Default::default(),
    }),
    primitive: wgpu::PrimitiveState::default(),     // triangle list
    depth_stencil: None,
    multisample: wgpu::MultisampleState::default(),
    multiview: None,
    cache: None,
});

Descriptors are plain structs with public fields, filled in with struct literal syntax and ..Default::default() for the rest. They borrow what they reference (&shader, &[...]), so, like ash's create-info structs, they cannot outlive their contents.

Each frame:

let frame = surface.get_current_texture()?;
let view = frame.texture.create_view(&Default::default());
let mut encoder = device.create_command_encoder(&Default::default());
{
    let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
        label: Some("main"),
        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
            view: &view,
            resolve_target: None,
            ops: wgpu::Operations {
                load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.1, g: 0.1, b: 0.12, a: 1.0 }),
                store: wgpu::StoreOp::Store,
            },
            depth_slice: None,
        })],
        ..Default::default()
    });
    pass.set_pipeline(&pipeline);
    pass.draw(0..3, 0..1);                 // vertices 0..3, instances 0..1
}                                          // the pass ends here, when `pass` is dropped
queue.submit([encoder.finish()]);
frame.present();

And the shader, triangle.wgsl:

@vertex
fn vs_main(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
    let x = f32(i32(i) - 1) * 0.5;
    let y = f32(i32(i & 1u) * 2 - 1) * 0.5;
    return vec4<f32>(x, y, 0.0, 1.0);
}

@fragment
fn fs_main() -> @location(0) vec4<f32> {
    return vec4<f32>(1.0, 0.5, 0.2, 1.0);
}

Ownership in the API

The wgpu API uses Rust's rules to make several classes of GPU bug impossible or detectable. Three examples.

A render pass borrows its encoder. begin_render_pass takes &mut CommandEncoder and returns a RenderPass<'_> that keeps that mutable borrow alive. While the pass exists, you cannot record anything else into the encoder or finish it. "End the render pass before starting a copy" is enforced by the borrow checker, and "end" is simply the end of the pass's scope. Here is the same pattern in miniature:

struct CommandEncoder { commands: Vec<String> }
struct RenderPass<'enc> { encoder: &'enc mut CommandEncoder }

impl CommandEncoder {
    fn begin_render_pass(&mut self, name: &str) -> RenderPass<'_> {
        self.commands.push(format!("begin {name}"));
        RenderPass { encoder: self }
    }
    fn copy_buffer(&mut self) { self.commands.push("copy".into()); }
    fn finish(self) -> Vec<String> { self.commands }
}

impl RenderPass<'_> {
    fn draw(&mut self, n: u32) { self.encoder.commands.push(format!("draw {n}")); }
}

impl Drop for RenderPass<'_> {
    fn drop(&mut self) { self.encoder.commands.push("end".into()); }
}

fn main() {
    let mut encoder = CommandEncoder { commands: vec![] };
    {
        let mut pass = encoder.begin_render_pass("main");
        pass.draw(3);
        // encoder.copy_buffer();   // error: `encoder` is already borrowed by `pass`
    }
    encoder.copy_buffer();
    println!("{:?}", encoder.finish());
}

Uncomment the line and the compiler refuses: the encoder is mutably borrowed by pass. In Vulkan, recording a copy inside a render pass is a validation error at best and a GPU hang at worst. (Recent wgpu versions also offer pass.forget_lifetime() for code that needs to store passes, and then check this at run time instead.)

Handles are reference counted. Buffer, Texture, BindGroup and the rest are cheap-to-clone handles to reference-counted objects. Dropping your Buffer while a submitted command buffer still uses it is fine: wgpu keeps it alive until that submission completes, then frees it. This is the deletion queue from the Vulkan chapter, built in.

Device and friends are Send + Sync. You can create resources and record command encoders on worker threads, then submit from one. The type system says which objects can cross threads, so a parallel renderer needs no "which thread owns the context?" documentation.

What wgpu does not catch at compile time (wrong buffer usage flags, bind groups that do not match the pipeline layout, out-of-bounds draws) it catches at run time with validation, as an error you can handle or a panic with a readable message, never as undefined behavior. That is the guarantee: safe wgpu code cannot cause UB on the GPU, even with wrong arguments.

Uniforms and bind groups

Uniform data goes into a buffer, and a bind group connects buffers and textures to a shader's @group(n) @binding(m) slots. The CPU-side struct must match WGSL's layout rules, which you check with bytemuck and const assertions (see Math and SIMD):

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Camera {
    view_proj: [[f32; 4]; 4],   // mat4x4<f32>
    position: [f32; 3],         // vec3<f32>: 16-byte aligned in WGSL
    _pad: f32,
}
const _: () = assert!(std::mem::size_of::<Camera>() == 80);

use wgpu::util::DeviceExt;   // for create_buffer_init
let camera_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
    label: Some("camera"),
    contents: bytemuck::bytes_of(&camera),
    usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});

let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
    label: Some("camera"),
    layout: &pipeline.get_bind_group_layout(0),
    entries: &[wgpu::BindGroupEntry { binding: 0, resource: camera_buffer.as_entire_binding() }],
});

// Each frame: update and bind.
queue.write_buffer(&camera_buffer, 0, bytemuck::bytes_of(&camera));
pass.set_bind_group(0, &bind_group, &[]);
struct Camera {
    view_proj: mat4x4<f32>,
    position: vec3<f32>,
};
@group(0) @binding(0) var<uniform> camera: Camera;

queue.write_buffer is the easy path for small, frequent updates: wgpu copies the data into a staging area and schedules the copy before the next submission, so you do not manage staging buffers or worry about overwriting data the GPU is reading.

Shaders: WGSL, naga and SPIR-V

WGSL is WebGPU's shading language. It reads like a mix of Rust and HLSL, and it is the native input. Other languages are supported through naga, the shader translator inside wgpu (also usable on its own):

InputHow
WGSLShaderSource::Wgsl, native
GLSLShaderSource::Glsl (feature glsl), through naga
SPIR-VShaderSource::SpirV (feature spirv), or create_shader_module_passthrough to skip translation on Vulkan
HLSLCompile to SPIR-V with dxc first

naga validates every shader when the module is created and reports errors with the source span, so a typo is a clean error at load time with the line underlined. The naga command-line tool (cargo install naga-cli) converts between WGSL, SPIR-V, GLSL, HLSL and MSL, which is handy for inspecting what your shader becomes on each back end.

For hot-reloading shaders during development, load the WGSL from disk instead of include_str! and recreate the pipeline when the file changes (Hot reloading). Use device.push_error_scope / pop_error_scope around module creation to turn validation errors into a Result instead of a panic, so a broken shader does not end the session.

Running on the web

The same wgpu code compiles to WebAssembly and runs in the browser:

rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli     # or use trunk, which wraps the whole flow
cargo build --target wasm32-unknown-unknown --release

Things that differ on the web:

  • There is no blocking: pollster::block_on does not work. Spawn the async setup with wasm_bindgen_futures::spawn_local.
  • The window is a <canvas>; winit's web backend handles it.
  • Some features are not available in browsers (push constants, some texture formats, non-uniform indexing). adapter.features() and adapter.limits() tell you what you have, and code should check them as it would check Vulkan extensions.

Summary

C++ / Vulkanwgpu
Vulkan, D3D12, Metal, GL back endsOne API, back end chosen at run time
Dawn (C++ WebGPU)wgpu (Rust WebGPU)
Barriers and layout transitionsAutomatic
Fences and deletion queues for resource lifetimeAutomatic (reference counted handles)
Render pass begin/endRenderPass borrows the encoder; ends on drop
Descriptor setsBind groups
GLSL/HLSL → SPIR-VWGSL native; GLSL/SPIR-V through naga
Validation layers (optional)Validation always on; errors, never UB

Exercises

  1. In the miniature encoder example, uncomment encoder.copy_buffer() inside the pass and read the error. Then add a ComputePass type that also borrows the encoder, and check that you cannot have a render pass and a compute pass open at once.
  2. Clone the wgpu repository and run the hello_triangle example (cargo run --bin wgpu-examples hello_triangle). Change the clear color, then change the shader to output a color from the vertex index.
  3. Add a time uniform to the triangle: a #[repr(C)] struct with an f32 and enough padding for WGSL's 16-byte uniform alignment, a buffer, a bind group, and a queue.write_buffer each frame. Write a const assertion for its size.

VR and AR with OpenXR

OpenXR is the Khronos standard API for virtual and augmented reality: headsets (Meta Quest, Valve Index, Pico, Varjo), their controllers, hand tracking, and the compositor that shows your rendered images in the headset. Like Vulkan, it is a C API with a loader, extensions and explicit handles, and it is usually used together with Vulkan (or D3D11/12, OpenGL): OpenXR provides the poses, timing and swapchain images; your renderer draws into them.

Rust has two layers of bindings, maintained in the same repository (openxrs):

CrateLikeWhat it gives you
openxr-sysopenxr.hRaw C types, constants and function pointer types, generated from xr.xml. Everything is unsafe.
openxrA thin C++ wrapperOwned handles with Drop, Result errors, typed actions, a session generic over the graphics API. Re-exports openxr-sys as openxr::sys.

This is the same split as ash (Vulkan) versus a safe wrapper, except that openxr is already a reasonably safe layer, so most code uses it and only drops to openxr::sys for extensions it does not wrap.

This chapter covers:

  • loading the runtime and creating an instance,
  • connecting OpenXR to a Vulkan renderer,
  • the session state machine and the frame loop,
  • input with actions, and poses in spaces,
  • projection and view matrices from OpenXR's FOV and pose,
  • how the Rust types encode OpenXR's rules,
  • using openxr-sys for unwrapped extensions, and building for Android (Quest).

The openxr crate's API changes between versions (it is at 0.19 at the time of writing). The code below shows the shape of the API; the examples in the repository are a complete, maintained reference, including a full Vulkan renderer (vulkan.rs).

The OpenXR model in one table

If you have used the C API, the mapping is direct:

OpenXR Copenxr crateNotes
Loader (openxr_loader.dll/.so)xr::EntryEntry::load() (dynamic) or Entry::linked() (static)
XrInstancexr::InstanceOwns the function table; cheap to clone (reference counted)
XrSystemIdxr::SystemIdA plain ID, not a handle: the headset
XrSessionxr::Session<G>G is the graphics API: xr::Vulkan, xr::D3D11, xr::OpenGL, xr::Headless
xrWaitFrame / xrBeginFrame + xrEndFramexr::FrameWaiter / xr::FrameStream<G>Two separate objects; see below
XrSwapchainxr::Swapchain<G>Images are G::SwapchainImage (a VkImage for Vulkan)
XrActionSet, XrActionxr::ActionSet, xr::Action<T>T is bool, f32, xr::Vector2f, xr::Posef or xr::Haptic
XrSpacexr::SpaceReference spaces (STAGE, LOCAL, VIEW) and action spaces
XrResultResult<T, xr::sys::Result>? instead of XR_FAILED(...) checks
xrDestroy*DropChildren keep their parent alive

Loading and creating an instance

use openxr as xr;

// Load the system's OpenXR loader (the runtime is chosen by the loader:
// SteamVR, Meta Quest Link, Monado, ...).
let entry = unsafe { xr::Entry::load()? };

// Ask what the runtime supports, and enable what we need.
let available = entry.enumerate_extensions()?;
assert!(available.khr_vulkan_enable2, "runtime does not support Vulkan");
let mut extensions = xr::ExtensionSet::default();
extensions.khr_vulkan_enable2 = true;

let instance = entry.create_instance(
    &xr::ApplicationInfo {
        application_name: "my-vr-app",
        application_version: 0,
        engine_name: "my-engine",
        engine_version: 0,
        api_version: xr::Version::new(1, 0, 0),
    },
    &extensions,
    &[],                                  // API layers
)?;
let props = instance.properties()?;
println!("runtime: {} {}", props.runtime_name, props.runtime_version);

// The headset. Fails with ERROR_FORM_FACTOR_UNAVAILABLE if none is connected.
let system = instance.system(xr::FormFactor::HEAD_MOUNTED_DISPLAY)?;

Compared with C:

  • xr::ExtensionSet is a struct with one bool field per known extension, plus other: Vec<String> for the rest. No string comparison loops, and a typo in an extension name is a compile error.
  • Strings are &str. The crate converts them to the fixed-size char arrays OpenXR wants, and returns an error if one is too long.
  • Every call returns Result, so a missing headset or an unsupported runtime reaches you through ? with the exact XrResult code.

Connecting to Vulkan

The Vulkan instance and device must be created through OpenXR (with XR_KHR_vulkan_enable2), because the runtime needs to add its own extensions and pick the physical device the headset is attached to. The openxr crate wraps the calls and leaves the Vulkan objects as raw handles, which you then hand to ash:

use ash::vk::{self, Handle};

// The runtime tells us which Vulkan versions it can work with.
let reqs = instance.graphics_requirements::<xr::Vulkan>(system)?;

let vk_entry = unsafe { ash::Entry::load()? };
let app_info = vk::ApplicationInfo::default().api_version(vk::make_api_version(0, 1, 2, 0));
let vk_instance_info = vk::InstanceCreateInfo::default().application_info(&app_info);

// OpenXR calls vkCreateInstance for us, adding the extensions it needs.
let vk_instance = unsafe {
    instance
        .create_vulkan_instance(
            system,
            std::mem::transmute(vk_entry.static_fn().get_instance_proc_addr),
            &vk_instance_info as *const _ as *const _,
        )?                                   // OpenXR error
        .map_err(vk::Result::from_raw)?      // Vulkan error
};
let vk_instance = unsafe {
    ash::Instance::load(vk_entry.static_fn(), vk::Instance::from_raw(vk_instance as _))
};

// The physical device that drives the headset.
let physical_device = vk::PhysicalDevice::from_raw(
    unsafe { instance.vulkan_graphics_device(system, vk_instance.handle().as_raw() as _)? } as _,
);
// ... create the logical device the same way, with create_vulkan_device ...

let (session, mut frame_waiter, mut frame_stream) = unsafe {
    instance.create_session::<xr::Vulkan>(
        system,
        &xr::vulkan::SessionCreateInfo {
            instance: vk_instance.handle().as_raw() as _,
            physical_device: physical_device.as_raw() as _,
            device: device.handle().as_raw() as _,
            queue_family_index,
            queue_index: 0,
        },
    )?
};

This is the most unsafe part of an OpenXR program, and it is unsafe for a real reason: OpenXR and ash each have their own copy of the Vulkan handle types, and the code converts between them through raw integers (as_raw/from_raw). The compiler cannot check that the VkDevice you pass really came from that VkInstance. Wrap this setup in one function that returns your renderer's safe types, and the rest of the program never sees it.

The G parameter of Session<G> is the payoff: a Session<xr::Vulkan> only produces swapchains whose images are VkImages, and only accepts a Vulkan SessionCreateInfo. Mixing graphics APIs is a type error, not a runtime crash.

The session state machine

An OpenXR session moves through states the runtime controls: the user puts the headset on or takes it off, opens the system menu, or another app takes focus. You learn about it from events, and you must respond: begin the session when it is READY, end it when it is STOPPING, exit on EXITING or LOSS_PENDING. Here is the logic as plain Rust, with a stand-in for the runtime's events:

#[derive(Clone, Copy, Debug, PartialEq)]
enum SessionState { Idle, Ready, Synchronized, Visible, Focused, Stopping, Exiting }

#[derive(Debug, Default)]
struct App { running: bool, should_render: bool, accepts_input: bool, quit: bool }

impl App {
    fn on_state_changed(&mut self, state: SessionState) {
        match state {
            SessionState::Ready => { self.running = true; println!("  -> session.begin()"); }
            SessionState::Stopping => { self.running = false; println!("  -> session.end()"); }
            SessionState::Exiting => self.quit = true,
            _ => {}
        }
        // VISIBLE: frames are shown. FOCUSED: frames are shown and we get input.
        self.should_render = matches!(state, SessionState::Visible | SessionState::Focused);
        self.accepts_input = state == SessionState::Focused;
    }
}

fn main() {
    use SessionState::*;
    let mut app = App::default();
    // The user starts the app, puts the headset on, opens the system menu,
    // closes it, then quits.
    for s in [Idle, Ready, Synchronized, Visible, Focused, Visible, Focused, Visible, Synchronized, Stopping, Idle, Exiting] {
        app.on_state_changed(s);
        println!("{s:?}: running={} render={} input={}", app.running, app.should_render, app.accepts_input);
        if app.quit { break; }
    }
}

With the real crate, the event loop at the top of each frame looks like this:

let mut event_buffer = xr::EventDataBuffer::new();
while let Some(event) = instance.poll_event(&mut event_buffer)? {
    match event {
        xr::Event::SessionStateChanged(e) => match e.state() {
            xr::SessionState::READY => {
                session.begin(xr::ViewConfigurationType::PRIMARY_STEREO)?;
                running = true;
            }
            xr::SessionState::STOPPING => {
                session.end()?;
                running = false;
            }
            xr::SessionState::EXITING | xr::SessionState::LOSS_PENDING => break 'main_loop,
            _ => {}
        },
        xr::Event::InstanceLossPending(_) => break 'main_loop,
        _ => {}
    }
}

poll_event borrows event_buffer, and the returned xr::Event<'_> borrows it in turn. In C, the event structure is overwritten by the next xrPollEvent, and reading a stale one is a silent bug; here, holding an event across the next poll is a borrow error.

The frame loop

Each frame has three steps. wait blocks until the runtime wants a new frame and returns the predicted display time, the moment the frame will appear in the headset. You render for that time, not for "now":

let view_type = xr::ViewConfigurationType::PRIMARY_STEREO;

// 1. Throttle to the headset's refresh rate and get the predicted display time.
let frame_state = frame_waiter.wait()?;
// 2. Tell the compositor we are starting to render.
frame_stream.begin()?;

if !frame_state.should_render {
    // Not visible (e.g. headset off): submit an empty frame.
    frame_stream.end(frame_state.predicted_display_time, blend_mode, &[])?;
    continue;
}

// Where are the eyes going to be at display time?
let (_flags, views) = session.locate_views(view_type, frame_state.predicted_display_time, &stage)?;

// Get a swapchain image to render into (one image with 2 array layers, one per eye).
let image_index = swapchain.acquire_image()?;
swapchain.wait_image(xr::Duration::INFINITE)?;
renderer.draw_stereo(images[image_index as usize], &views);   // your Vulkan code
swapchain.release_image()?;

// 3. Hand the image to the compositor, with the poses we rendered with.
let rect = xr::Rect2Di {
    offset: xr::Offset2Di { x: 0, y: 0 },
    extent: xr::Extent2Di { width: w as i32, height: h as i32 },
};
frame_stream.end(
    frame_state.predicted_display_time,
    blend_mode,
    &[&xr::CompositionLayerProjection::new().space(&stage).views(&[
        xr::CompositionLayerProjectionView::new()
            .pose(views[0].pose)
            .fov(views[0].fov)
            .sub_image(xr::SwapchainSubImage::new().swapchain(&swapchain).image_array_index(0).image_rect(rect)),
        xr::CompositionLayerProjectionView::new()
            .pose(views[1].pose)
            .fov(views[1].fov)
            .sub_image(xr::SwapchainSubImage::new().swapchain(&swapchain).image_array_index(1).image_rect(rect)),
    ])],
)?;

Why are FrameWaiter and FrameStream separate objects? OpenXR allows xrWaitFrame to be called on one thread while another thread calls xrBeginFrame/xrEndFrame for the previous frame; that pipelining is how engines hide CPU latency. The crate gives each half its own owned value, both Send, and both methods take &mut self. So you can move the waiter to a different thread from the stream, but you cannot call wait from two threads at once. The spec's "externally synchronized" rules become ownership, exactly like command pools in the Vulkan chapter.

The swapchain follows the same idea: acquire_image, wait_image and release_image take &mut self, so two threads cannot interleave them on one swapchain.

Input: actions and spaces

OpenXR input is abstract: you define actions ("grab", "teleport", "hand pose"), and suggest bindings to physical inputs for each controller type ("interaction profile"). The runtime may remap them. In the crate, the action's value type is a type parameter, so you cannot read a pose action as a float:

let action_set = instance.create_action_set("gameplay", "Gameplay", 0)?;
let left = instance.string_to_path("/user/hand/left")?;
let right = instance.string_to_path("/user/hand/right")?;

let grab = action_set.create_action::<f32>("grab", "Grab", &[left, right])?;
let hand_pose = action_set.create_action::<xr::Posef>("hand_pose", "Hand pose", &[left, right])?;

// Suggested bindings for the generic controller profile every runtime supports.
instance.suggest_interaction_profile_bindings(
    instance.string_to_path("/interaction_profiles/khr/simple_controller")?,
    &[
        xr::Binding::new(&grab, instance.string_to_path("/user/hand/left/input/select/click")?),
        xr::Binding::new(&grab, instance.string_to_path("/user/hand/right/input/select/click")?),
        xr::Binding::new(&hand_pose, instance.string_to_path("/user/hand/left/input/grip/pose")?),
        xr::Binding::new(&hand_pose, instance.string_to_path("/user/hand/right/input/grip/pose")?),
    ],
)?;
session.attach_action_sets(&[&action_set])?;

// A pose action becomes a space you can locate relative to another space.
let left_hand = hand_pose.create_space(session.clone(), left, xr::Posef::IDENTITY)?;
let stage = session.create_reference_space(xr::ReferenceSpaceType::STAGE, xr::Posef::IDENTITY)?;

// Each frame:
session.sync_actions(&[(&action_set).into()])?;
let squeeze = grab.state(&session, left)?;            // xr::ActionState<f32>
if squeeze.is_active && squeeze.current_state > 0.8 {
    let loc = left_hand.locate(&stage, frame_state.predicted_display_time)?;
    if loc.location_flags.contains(xr::SpaceLocationFlags::POSITION_VALID) {
        world.grab_at(loc.pose.position);
    }
}

Notice location_flags: a pose can be invalid (controller out of tracking range) or only orientation-valid. The flags make that explicit, and a Rust helper returning Option<Posef> turns "forgot to check the flag" into a type error for the rest of your engine.

From FOV and pose to matrices

OpenXR describes each eye with a pose (position plus orientation quaternion, in the space you asked for) and an asymmetric field of view: four angles in radians, left and down negative. Your renderer needs a view matrix and a projection matrix. This is the part every XR renderer writes, and it is plain math you can run here.

The projection follows the OpenXR SDK's xr_linear.h, for Vulkan or wgpu clip space (y pointing down, depth from 0 to 1):

#[derive(Clone, Copy, Debug)]
pub struct Fov { pub angle_left: f32, pub angle_right: f32, pub angle_up: f32, pub angle_down: f32 }

#[derive(Clone, Copy, Debug)]
pub struct Posef { pub orientation: [f32; 4], pub position: [f32; 3] } // quaternion x, y, z, w

type Mat4 = [[f32; 4]; 4];   // column-major, like GLSL/WGSL and glam

/// Asymmetric perspective projection for Vulkan clip space (y down, z in 0..1).
pub fn projection(fov: Fov, near: f32, far: f32) -> Mat4 {
    let (l, r) = (fov.angle_left.tan(), fov.angle_right.tan());
    let (u, d) = (fov.angle_up.tan(), fov.angle_down.tan());
    let w = r - l;
    let h = d - u;                 // negative: flips y, because Vulkan's y points down
    [
        [2.0 / w, 0.0, 0.0, 0.0],
        [0.0, 2.0 / h, 0.0, 0.0],
        [(r + l) / w, (u + d) / h, -far / (far - near), -1.0],
        [0.0, 0.0, -(far * near) / (far - near), 0.0],
    ]
}

/// Rotate v by the unit quaternion q.
fn rotate(q: [f32; 4], v: [f32; 3]) -> [f32; 3] {
    let [x, y, z, w] = q;
    let t = [2.0 * (y * v[2] - z * v[1]), 2.0 * (z * v[0] - x * v[2]), 2.0 * (x * v[1] - y * v[0])];
    [
        v[0] + w * t[0] + (y * t[2] - z * t[1]),
        v[1] + w * t[1] + (z * t[0] - x * t[2]),
        v[2] + w * t[2] + (x * t[1] - y * t[0]),
    ]
}

/// The view matrix is the inverse of the eye's pose: rotate by the conjugate,
/// after translating by -position.
pub fn view(pose: Posef) -> Mat4 {
    let [x, y, z, w] = pose.orientation;
    let inv = [-x, -y, -z, w];
    let cols = [rotate(inv, [1.0, 0.0, 0.0]), rotate(inv, [0.0, 1.0, 0.0]), rotate(inv, [0.0, 0.0, 1.0])];
    let t = rotate(inv, pose.position);
    [
        [cols[0][0], cols[0][1], cols[0][2], 0.0],
        [cols[1][0], cols[1][1], cols[1][2], 0.0],
        [cols[2][0], cols[2][1], cols[2][2], 0.0],
        [-t[0], -t[1], -t[2], 1.0],
    ]
}

fn transform(m: &Mat4, p: [f32; 3]) -> [f32; 3] {
    let mut o = [0.0f32; 4];
    for row in 0..4 {
        o[row] = m[0][row] * p[0] + m[1][row] * p[1] + m[2][row] * p[2] + m[3][row];
    }
    [o[0] / o[3], o[1] / o[3], o[2] / o[3]]
}

fn main() {
    // A typical left eye: the field of view extends further outward (left) than toward the nose.
    let fov = Fov { angle_left: -0.94, angle_right: 0.77, angle_up: 0.87, angle_down: -0.96 };
    let proj = projection(fov, 0.05, 100.0);

    // The eye 1.6 m above the floor, 3 cm left of center, turned 90° to the left (about +y).
    let half = std::f32::consts::FRAC_PI_4;
    let pose = Posef { orientation: [0.0, half.sin(), 0.0, half.cos()], position: [-0.03, 1.6, 0.0] };
    let view = view(pose);

    // A point 2 m to the left of the eye, at eye height, is straight ahead after turning left.
    let p = [-2.03, 1.6, 0.0];
    let eye_space = transform(&view, p);
    println!("eye space: {:?}", eye_space.map(|v| (v * 1000.0).round() / 1000.0));
    println!("clip/NDC:  {:?}", transform(&proj, eye_space));
    // The left edge of the FOV at 1 m maps to x = -1:
    println!("left edge: {:?}", transform(&proj, [-(0.94f32.tan()), 0.0, -1.0]));
}

With glam, the same projection is a Mat4::from_cols_array_2d(&projection(...)) and the view is Mat4::from_rotation_translation(q, p).inverse(); the hand-written version is shown so you can see exactly what OpenXR's numbers mean. Two pitfalls that are not Rust-specific but cost everyone a day:

  • OpenXR's FOV is not symmetric. A symmetric perspective(fovy, aspect) looks almost right and makes users feel sick.
  • angle_down and angle_left are negative. Clip-space y is down in Vulkan and up in OpenGL; use the GL variant of the formula (h = u - d, depth -1..1) for OpenGL.

How the types encode the rules

OpenXR ruleHow the openxr crate expresses it
Destroy children before the parentHandles hold an Arc of their instance/session; Drop destroys them
A session uses exactly one graphics APISession<G>, Swapchain<G>, FrameStream<G> are generic over G
xrWaitFrame and xrBeginFrame are externally synchronizedSeparate FrameWaiter and FrameStream, methods take &mut self
Event data is overwritten by the next pollEvent<'a> borrows the EventDataBuffer
Actions have a fixed value typeAction<T>; state() returns ActionState<T>
String paths must be internedxr::Path, created by instance.string_to_path
Structs need type and nextBuilders such as CompositionLayerProjection::new() fill them in

What it does not check: valid usage that depends on runtime state (calling locate_views before the session is running returns an error), and anything on the graphics side, which is your renderer's job. The validation layer (XR_APILAYER_LUNARG_core_validation) works with Rust programs as with C++.

Dropping to openxr-sys

When you need an extension the safe crate does not wrap yet, use the raw function pointers. openxr::sys has every type and function pointer type from openxr.h; you load the function with xrGetInstanceProcAddr and call it in unsafe, exactly as in C:

use openxr as xr;
use openxr::sys;

/// XrResult codes below zero are errors.
fn check(r: sys::Result) -> Result<(), sys::Result> {
    if r.into_raw() >= 0 { Ok(()) } else { Err(r) }
}

// Load an extension function by name (here: XR_FB_display_refresh_rate).
let mut raw: Option<sys::pfn::VoidFunction> = None;
check(unsafe {
    (entry.fp().get_instance_proc_addr)(
        instance.as_raw(),
        c"xrRequestDisplayRefreshRateFB".as_ptr(),
        &mut raw,
    )
})?;
let request_refresh_rate: sys::pfn::RequestDisplayRefreshRateFB =
    unsafe { std::mem::transmute(raw.expect("function not found")) };

// SAFETY: the session is live, and the extension was enabled at instance creation.
check(unsafe { request_refresh_rate(session.as_raw(), 90.0) })?;

Before writing this, check instance.exts(): many extensions (hand tracking, passthrough, refresh rate, foveation) already have typed wrappers or at least loaded function tables there, so you can call (fp.request_display_refresh_rate)(...) without the transmute. Treat any raw call the way you treated FFI in FFI with C and C++: one small function, a SAFETY comment stating the preconditions, a safe signature on the outside.

Building for Meta Quest (Android)

Standalone headsets run Android, so the target is aarch64-linux-android (see Toolchain setup). The pieces:

  • Loader: Quest uses the Khronos standard Android loader. Enable the crate's linked feature and ship libopenxr_loader.so in the APK, or use Entry::load() and bundle it as a library.
  • App glue: the android-activity crate provides the android_main entry point and the lifecycle events (winit uses it on Android too). OpenXR needs the Java VM and activity pointers on Android: pass them through xr::Entry::initialize_android_loader() and the session's Android create info, as the crate's examples show.
  • Packaging: xbuild or cargo-apk builds the APK; add the VR intent categories and the com.oculus.intent.category.VR (and the Khronos org.khronos.openxr.intent.category.IMMERSIVE_HMD) to the manifest.

Bevy users can skip most of this: the bevy_mod_openxr project integrates OpenXR with Bevy's wgpu renderer and handles the session and frame loop.

Summary

C / C++Rust
openxr.h, openxr_platform.hopenxr-sys (raw), re-exported as openxr::sys
Hand-written C++ wrapper / OpenXR-Hppopenxr crate
XR_FAILED(result) checksResult<T, sys::Result> and ?
xrDestroy* in reverse orderDrop; children keep parents alive
XrSession + XrGraphicsBinding*Session<xr::Vulkan> etc.
xrWaitFrame / xrBeginFrame / xrEndFrameFrameWaiter::wait, FrameStream::begin/end
Event buffer reused by xrPollEventEvent<'_> borrowing EventDataBuffer
xrGetInstanceProcAddr for extensionsinstance.exts(), or sys::pfn + transmute
xr_linear.h mathglam, or the few lines above

Exercises

  1. In the session-state example, add a LossPending state that quits like Exiting, and make on_state_changed return a Command enum (Begin, End, Quit, Nothing) instead of printing. Why is that easier to test?
  2. Write the OpenGL variant of projection (y up, depth -1..1) and check with transform that the near and far planes map to -1 and 1.
  3. Write fn locate_valid(loc: &xr::SpaceLocation) -> Option<xr::Posef> (with your own stand-in types if you do not have the crate) that returns a pose only when both the position and orientation are valid. Where in a game would you call it?

The game loop, windows and global state

A C++ game's main usually looks like this: create a window with SDL or GLFW, then while (!quit) { poll events; update; render; }, with the engine's subsystems reachable through singletons. Rust changes two of those pieces. The standard windowing crate, winit, owns the loop and calls you, rather than you calling it. And singletons are mostly replaced by passing context explicitly, because mutable global state is exactly what the borrow checker is designed to control.

This chapter covers:

  • winit's event loop and the ApplicationHandler trait,
  • a fixed timestep with interpolation,
  • frame pacing and vsync,
  • where global state goes when there are no singletons.

winit: the loop calls you

winit is the Rust equivalent of the windowing half of GLFW or SDL: windows, input, DPI, and the platform event loop, on Windows, macOS, Linux (X11 and Wayland), Android, iOS and the web. Since version 0.30, you implement a trait and hand it to the event loop:

use std::sync::Arc;
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::{Window, WindowId};

#[derive(Default)]
struct App {
    window: Option<Arc<Window>>,
    game: Option<Game>,          // renderer + world, created once we have a window
}

impl ApplicationHandler for App {
    // Called when the app may create windows (at startup; again after suspend on mobile).
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap());
        self.game = Some(Game::new(window.clone()));
        self.window = Some(window);
    }

    fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
        let Some(game) = &mut self.game else { return };
        match event {
            WindowEvent::CloseRequested => event_loop.exit(),
            WindowEvent::Resized(size) => game.resize(size.width, size.height),
            WindowEvent::KeyboardInput { event, .. } => game.input.key(event),
            WindowEvent::RedrawRequested => {
                game.frame();                                   // update + render
                self.window.as_ref().unwrap().request_redraw(); // ask for the next one
            }
            _ => {}
        }
    }
}

fn main() -> Result<(), winit::error::EventLoopError> {
    let event_loop = EventLoop::new()?;
    event_loop.set_control_flow(ControlFlow::Poll);   // run continuously, like a game
    event_loop.run_app(&mut App::default())
}

Why the inversion? Some platforms (macOS, iOS, the web) do not let a program own the main loop: the OS calls the application. winit adopts that model everywhere, so the same code runs on all of them. In practice it changes little: RedrawRequested is your "frame" callback, and calling request_redraw() at the end of each frame keeps it running.

All state lives in the App struct. There are no globals; the event loop owns App, and each callback gets &mut self. That is the start of the answer to "where does global state go", which this chapter returns to below.

If you prefer the C++ shape, the sdl2 and glfw crates are bindings to the libraries you know, with a classic poll_events() loop.

Fixed timestep

Physics and gameplay usually update at a fixed rate, decoupled from the display. The accumulator pattern ("Fix your timestep!") translates directly:

use std::time::Duration;

#[derive(Clone, Copy, Debug, Default)]
struct State { pos: f32, vel: f32 }

fn integrate(s: State, dt: f32) -> State {
    let acc = -9.81;
    State { vel: s.vel + acc * dt, pos: s.pos + s.vel * dt }
}

fn lerp(a: State, b: State, t: f32) -> State {
    State { pos: a.pos + (b.pos - a.pos) * t, vel: a.vel + (b.vel - a.vel) * t }
}

struct Clock {
    step: Duration,
    accumulator: Duration,
    max_frame: Duration,       // clamp, so a long stall does not cause a spiral of death
}

impl Clock {
    /// Returns how many fixed steps to run this frame, and the interpolation factor.
    fn advance(&mut self, frame_time: Duration) -> (u32, f32) {
        self.accumulator += frame_time.min(self.max_frame);
        let mut steps = 0;
        while self.accumulator >= self.step {
            self.accumulator -= self.step;
            steps += 1;
        }
        (steps, self.accumulator.as_secs_f32() / self.step.as_secs_f32())
    }
}

fn main() {
    let mut clock = Clock {
        step: Duration::from_secs_f64(1.0 / 60.0),
        accumulator: Duration::ZERO,
        max_frame: Duration::from_millis(250),
    };
    let (mut previous, mut current) = (State { pos: 10.0, vel: 0.0 }, State { pos: 10.0, vel: 0.0 });

    // Simulated frame times: a 144 Hz display with one 40 ms hitch.
    let frames = [6.9, 6.9, 6.9, 40.0, 6.9, 6.9];
    for ms in frames {
        let (steps, alpha) = clock.advance(Duration::from_secs_f64(ms / 1000.0));
        for _ in 0..steps {
            previous = current;
            current = integrate(current, clock.step.as_secs_f32());
        }
        let shown = lerp(previous, current, alpha);
        println!("frame {ms:>4} ms: {steps} steps, alpha {alpha:.2}, render pos {:.4}", shown.pos);
    }
}

In a real loop, frame_time comes from std::time::Instant:

let now = Instant::now();
let frame_time = now - self.last_frame;   // Instant - Instant = Duration
self.last_frame = now;

Instant is monotonic (QueryPerformanceCounter, clock_gettime(CLOCK_MONOTONIC)) and Duration is an exact integer number of nanoseconds, so there is no accumulated floating-point drift in the accumulator. Convert to f32 seconds only at the point of use.

Frame pacing

  • Vsync is a surface setting, not a loop setting: PresentMode::Fifo in wgpu, VK_PRESENT_MODE_FIFO_KHR in Vulkan, the swap interval in glutin. Presenting blocks until a vsync slot is available, which paces the loop.
  • Without vsync, ControlFlow::WaitUntil(next_frame_instant) tells winit to sleep until the next frame is due, rather than spinning at 100% CPU.
  • For tools and editors that only need to redraw on input, use ControlFlow::Wait and call request_redraw() only when something changes. The event loop then sleeps, like a normal desktop application.
  • std::thread::sleep has the usual OS granularity (about 1 ms on Linux and macOS; on Windows, Rust requests high-resolution timers where available). For precise frame caps, sleep until slightly before the deadline, then spin.

Where global state goes

C++ engines are full of singletons: Renderer::Get(), g_Input, AssetManager::Instance(). Rust makes mutable globals deliberately awkward: a static mut can only be accessed in unsafe code, and taking a reference to one is rejected by default in the 2024 edition, because two &mut to the same global from different call sites (or threads) is undefined behavior. The idiomatic options, in order of preference:

1. Pass a context

Most "global" state is really per-game state that you can own in one struct and pass down:

struct Input { jump_pressed: bool }
struct Audio { queued: Vec<&'static str> }
struct Time { dt: f32, frame: u64 }

struct Ctx<'a> {
    input: &'a Input,
    audio: &'a mut Audio,
    time: &'a Time,
}

struct Player { y: f32, vy: f32 }

impl Player {
    fn update(&mut self, ctx: &mut Ctx) {
        if ctx.input.jump_pressed && self.y == 0.0 {
            self.vy = 5.0;
            ctx.audio.queued.push("jump.wav");
        }
        self.vy -= 9.81 * ctx.time.dt;
        self.y = (self.y + self.vy * ctx.time.dt).max(0.0);
    }
}

fn main() {
    let input = Input { jump_pressed: true };
    let mut audio = Audio { queued: vec![] };
    let time = Time { dt: 1.0 / 60.0, frame: 1 };
    let mut player = Player { y: 0.0, vy: 0.0 };

    let mut ctx = Ctx { input: &input, audio: &mut audio, time: &time };
    player.update(&mut ctx);
    println!("frame {}: y = {:.3}, sounds = {:?}", time.frame, player.y, audio.queued);
}

Every dependency is visible in the signature: Player::update reads input and time and writes audio. The compiler checks that nothing else holds &mut Audio during the call, and tests can construct a Ctx with fake input. This is the same idea as ECS resources (Res<Time>, ResMut<Audio> in bevy_ecs; see ECS), which are a context struct managed by the scheduler.

2. Immutable globals, initialized once

Configuration, lookup tables and other values that never change after startup can be globals safely, because shared read-only access cannot race:

use std::sync::OnceLock;
use std::collections::HashMap;

static CONFIG: OnceLock<HashMap<&'static str, f32>> = OnceLock::new();

fn config() -> &'static HashMap<&'static str, f32> {
    CONFIG.get_or_init(|| {
        println!("loading config (once)");
        HashMap::from([("gravity", 9.81), ("fov", 70.0)])
    })
}

// Fully compile-time tables need no initialization at all:
static GAMMA_LUT: [u8; 4] = [0, 21, 99, 255];

fn main() {
    println!("{} {}", config()["gravity"], config()["fov"]);
    println!("{:?}", GAMMA_LUT);
}

OnceLock is the thread-safe "initialize on first use" of a C++ function-local static, and LazyLock is the same with the initializer stored in the static itself: static TABLE: LazyLock<Vec<u32>> = LazyLock::new(build_table);.

3. Mutable globals, synchronized

For the few things that really are process-wide and mutable (a logger, a profiler, an allocation counter), wrap them in a synchronization type:

  • Atomics for counters and flags: static FRAMES: AtomicU64 = AtomicU64::new(0);
  • Mutex/RwLock for anything bigger: static LOG: Mutex<Vec<String>> = Mutex::new(Vec::new()); (Mutex::new is const, so no lazy initialization is needed).
  • thread_local! for per-thread state, such as a per-thread scratch allocator: thread_local! { static SCRATCH: RefCell<Vec<u8>> = RefCell::new(Vec::new()); }

The log and tracing crates are built this way: a global logger set once at startup, called from anywhere with log::info!(...).

C++ habit to unlearn

Do not reach for static mut to port a singleton. If a piece of state is mutated from many places, the Rust answer is to make those places receive it as a parameter. This is often a large refactor in a C++ codebase, but in a new Rust codebase it is the default and costs nothing, and it makes the data flow visible, which is what you need when you later parallelize.

Input handling

winit delivers input as events. Games usually convert them into a per-frame state snapshot that update code reads:

use std::collections::HashSet;

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
enum Key { W, A, S, D, Space }

#[derive(Default)]
struct Input {
    down: HashSet<Key>,
    pressed_this_frame: HashSet<Key>,
}

impl Input {
    fn on_key(&mut self, key: Key, is_down: bool) {
        if is_down {
            if self.down.insert(key) {          // insert returns false if already held
                self.pressed_this_frame.insert(key);
            }
        } else {
            self.down.remove(&key);
        }
    }
    fn end_frame(&mut self) { self.pressed_this_frame.clear(); }
    fn axis(&self, neg: Key, pos: Key) -> f32 {
        (self.down.contains(&pos) as i32 - self.down.contains(&neg) as i32) as f32
    }
}

fn main() {
    let mut input = Input::default();
    input.on_key(Key::D, true);
    input.on_key(Key::Space, true);
    input.on_key(Key::Space, true);             // OS key repeat: not a new press
    println!("x = {}, jump = {}", input.axis(Key::A, Key::D), input.pressed_this_frame.contains(&Key::Space));
    input.end_frame();
    println!("next frame jump = {}", input.pressed_this_frame.contains(&Key::Space));
    let _ = (Key::W, Key::S);
}

In winit, keys arrive as KeyEvent { physical_key, logical_key, state, repeat, .. }. Use physical_key (a KeyCode like KeyCode::KeyW, by position) for WASD movement so it works on AZERTY keyboards, and logical_key for text and shortcuts. For gamepads, use the gilrs crate.

Summary

C++Rust
SDL / GLFW window and loopwinit EventLoop + ApplicationHandler (or sdl2/glfw crates)
while (!quit) { ... }RedrawRequested + request_redraw(), ControlFlow::Poll
std::chrono::steady_clockstd::time::Instant, Duration
Singleton Get()Context passed as a parameter; ECS resources
Function-local staticOnceLock, LazyLock
Global mutable variableAtomic, Mutex, or thread_local!; static mut only with unsafe
glfwSwapInterval(1)PresentMode::Fifo (wgpu), swap interval (glutin)

Exercises

  1. Change the simulated frame times in the fixed-timestep example to a 30 Hz display (33.3 ms). How many steps run per frame? What happens to alpha?
  2. Add a ctx.time.frame-based cooldown to Player::update so the player can only jump every 30 frames. Which struct holds the "last jump frame"?
  3. Write a global frame counter with AtomicU64, increment it from two threads with std::thread::scope, and print the total. Then try the same with static mut COUNTER: u64 and read the compiler's error or warning.

Assets, build scripts and serialization

A C++ engine's build is more than compiling C++: shaders are compiled to SPIR-V or DXIL, textures are compressed, meshes are converted, and code is generated from schemas, all wired into CMake with add_custom_command. At run time, an asset manager loads the results, often on worker threads, and reloads them when they change. This chapter covers the Rust equivalents.

This chapter covers:

  • build.rs build scripts for shader compilation and code generation,
  • embedding files in the binary,
  • serialization with serde,
  • an asset cache with typed handles and background loading,
  • watching files for hot reload,
  • organizing an engine as a Cargo workspace.

Build scripts

A file named build.rs in a package root is compiled and run by Cargo before the package itself is compiled. It is ordinary Rust, so it can do anything: run a compiler, generate code, compile a C library with the cc crate (see FFI). It talks to Cargo by printing cargo:: lines to stdout.

Here is a build script that compiles every GLSL shader in shaders/ to SPIR-V with glslc:

// build.rs
use std::path::Path;
use std::process::Command;

fn main() {
    let out_dir = std::env::var("OUT_DIR").unwrap();   // Cargo's per-build scratch dir
    println!("cargo::rerun-if-changed=shaders");       // only rerun when shaders change

    for entry in std::fs::read_dir("shaders").unwrap() {
        let path = entry.unwrap().path();
        let ext = path.extension().and_then(|e| e.to_str());
        if !matches!(ext, Some("vert" | "frag" | "comp")) {
            continue;
        }
        let file_name = path.file_name().unwrap().to_str().unwrap();
        let output = Path::new(&out_dir).join(format!("{file_name}.spv"));
        let status = Command::new("glslc")
            .arg(&path)
            .arg("-o")
            .arg(&output)
            .status()
            .expect("glslc not found: install the Vulkan SDK");
        if !status.success() {
            panic!("shader compilation failed: {}", path.display());
        }
    }
}

The crate then embeds the results:

// src/shaders.rs
pub const MESH_VERT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/mesh.vert.spv"));
pub const MESH_FRAG: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/mesh.frag.spv"));

Things to know:

  • OUT_DIR is where build scripts write. Never write into src/: Cargo may build several configurations in parallel, and src/ is not a build directory.
  • cargo::rerun-if-changed=PATH limits reruns to changes in that path. Without any rerun-if line, the script reruns when any file in the package changes.
  • Build dependencies go in [build-dependencies] in Cargo.toml, separate from the crate's own dependencies. shaderc, cc, bindgen and naga are common ones.
  • Errors are reported by panicking or exiting with a non-zero code; Cargo shows the script's stderr. cargo::warning=message prints a warning without failing.
  • Environment for the crate: cargo::rustc-env=KEY=value sets a variable readable with env!("KEY") in the crate (a version string, a git hash).

A build script replaces add_custom_command plus the dependency tracking you would otherwise write in CMake. For heavy asset processing (texture compression of gigabytes of data), engines usually keep a separate asset cooker binary instead, run explicitly or by the editor, so cargo build stays fast.

Embedding files

Three macros read files at compile time, relative to the current source file:

MacroResultC++ equivalent
include_bytes!("logo.png")&'static [u8; N]xxd -i, #embed (C23)
include_str!("shader.wgsl")&'static str (must be UTF-8)Raw string with #include, #embed
include!("generated.rs")Rust code pasted in#include

Embedded data needs no file I/O and no path handling at run time, which makes it ideal for default assets, fonts, shaders and small tools. For large asset sets, load from disk so you can change assets without rebuilding.

A common pattern is to embed in release builds and load from disk in debug builds, for hot reloading:

fn shader_source(name: &str) -> std::borrow::Cow<'static, str> {
    #[cfg(not(debug_assertions))]
    {
        // In a real project: match name { "mesh" => include_str!("../shaders/mesh.wgsl"), ... }
        let _ = name;
        return std::borrow::Cow::Borrowed("/* embedded */");
    }
    #[cfg(debug_assertions)]
    {
        let path = format!("shaders/{name}.wgsl");
        std::fs::read_to_string(&path)
            .map(std::borrow::Cow::Owned)
            .unwrap_or_else(|e| std::borrow::Cow::Owned(format!("/* {path}: {e} */")))
    }
}

fn main() {
    println!("{}", shader_source("mesh"));
}

Cow<'static, str> ("clone on write") holds either a borrowed &'static str or an owned String, so both branches return the same type without copying the embedded text.

Serialization with serde

serde is the standard serialization framework. You derive Serialize and Deserialize on your types, and pick a format crate: serde_json, ron (Rusty Object Notation, popular for game data), toml, bincode or postcard (compact binary), rmp-serde (MessagePack). The derive generates code at compile time from the type definition, so there is no runtime reflection and no schema file. It is the replacement for the reflection macros and code generators C++ engines use for this (Macros explains derives).

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct MaterialDesc {
    shader: String,
    #[serde(default = "default_color")]
    base_color: [f32; 4],
    textures: Vec<TextureSlot>,
    #[serde(default)]
    double_sided: bool,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum TextureSlot {
    Albedo { path: String },
    Normal { path: String, strength: f32 },
}

fn default_color() -> [f32; 4] { [1.0; 4] }

let text = r#"(
    shader: "pbr",
    textures: [
        (kind: "albedo", path: "rock_albedo.ktx2"),
        (kind: "normal", path: "rock_normal.ktx2", strength: 0.8),
    ],
)"#;
let material: MaterialDesc = ron::from_str(text)?;
let as_json = serde_json::to_string_pretty(&material)?;

Points for C++ programmers:

  • Enums serialize naturally, including variants with data, which is awkward in most C++ serializers.
  • Errors are values with position information ("missing field shader at line 2 column 1"), not crashes or silently default-initialized fields.
  • The same derive works for every format. A level can be RON while you edit it and bincode when you ship it, with no code change.
  • Attributes customize the mapping: rename, default, skip, flatten, with = "module" for custom field encoding.

For zero-copy loading of large binary assets (the "mmap the file and cast it" technique), serde is the wrong tool. Use bytemuck on #[repr(C)] data (Math and SIMD) or the rkyv crate, which validates a byte buffer once and then gives you references into it.

An asset cache with typed handles

Engines refer to assets by handle, for the same reasons as game objects (Handles and arenas): assets load asynchronously, can be reloaded, and are shared by many users. Here is a small cache that loads on background threads and delivers results through a channel, all in the standard library:

use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::mpsc::{self, Receiver, Sender};
use std::thread;
use std::time::Duration;

pub struct Handle<T> { id: u32, _t: PhantomData<fn() -> T> }
impl<T> Clone for Handle<T> { fn clone(&self) -> Self { *self } }
impl<T> Copy for Handle<T> {}

pub enum Slot<T> { Loading, Ready(T), Failed(String) }

pub trait Asset: Send + 'static + Sized {
    fn load(path: &str) -> Result<Self, String>;
}

pub struct Assets<T: Asset> {
    by_path: HashMap<String, u32>,
    slots: Vec<Slot<T>>,
    tx: Sender<(u32, Result<T, String>)>,
    rx: Receiver<(u32, Result<T, String>)>,
}

impl<T: Asset> Assets<T> {
    pub fn new() -> Self {
        let (tx, rx) = mpsc::channel();
        Assets { by_path: HashMap::new(), slots: Vec::new(), tx, rx }
    }

    /// Returns immediately. Loading the same path twice returns the same handle.
    pub fn load(&mut self, path: &str) -> Handle<T> {
        if let Some(&id) = self.by_path.get(path) {
            return Handle { id, _t: PhantomData };
        }
        let id = self.slots.len() as u32;
        self.slots.push(Slot::Loading);
        self.by_path.insert(path.to_string(), id);
        let (tx, path) = (self.tx.clone(), path.to_string());
        thread::spawn(move || {
            let _ = tx.send((id, T::load(&path)));   // the receiver may be gone at shutdown
        });
        Handle { id, _t: PhantomData }
    }

    /// Call once per frame: moves finished loads into their slots.
    pub fn update(&mut self) {
        for (id, result) in self.rx.try_iter() {
            self.slots[id as usize] = match result {
                Ok(asset) => Slot::Ready(asset),
                Err(e) => Slot::Failed(e),
            };
        }
    }

    pub fn get(&self, h: Handle<T>) -> Option<&T> {
        match &self.slots[h.id as usize] {
            Slot::Ready(asset) => Some(asset),
            _ => None,
        }
    }

    pub fn status(&self, h: Handle<T>) -> &'static str {
        match &self.slots[h.id as usize] {
            Slot::Loading => "loading",
            Slot::Ready(_) => "ready",
            Slot::Failed(_) => "failed",
        }
    }
}

// A fake texture type whose "loading" takes a little time.
struct Texture { width: u32 }
impl Asset for Texture {
    fn load(path: &str) -> Result<Self, String> {
        thread::sleep(Duration::from_millis(20));
        if path.ends_with(".ktx2") { Ok(Texture { width: 512 }) } else { Err(format!("{path}: unknown format")) }
    }
}

fn main() {
    let mut textures: Assets<Texture> = Assets::new();
    let rock = textures.load("rock.ktx2");
    let rock_again = textures.load("rock.ktx2");
    let bad = textures.load("sky.bmp");

    for frame in 0..4 {
        textures.update();
        let width = textures.get(rock).map(|t| t.width);
        println!("frame {frame}: rock {} {:?}, sky {}", textures.status(rock), width, textures.status(bad));
        thread::sleep(Duration::from_millis(10));
    }
    assert_eq!(rock.id, rock_again.id);
}

What the types guarantee:

  • T: Send on Asset is required because the loaded value crosses from the worker thread to the main thread. A texture type holding an Rc would be rejected at compile time.
  • Handle<Texture> and Handle<Mesh> are different types, so they cannot be mixed up.
  • get returns Option<&T>: code that renders must decide what to do while an asset is still loading (skip it, or use a placeholder). It cannot forget.

A production version uses a thread pool (rayon, or the engine's job system) instead of a thread per load, adds reference counting to unload unused assets, and keeps generation numbers in handles. The bevy_asset crate is a full-featured example of this design.

Watching files

For hot reloading assets in development, the notify crate wraps the OS file-watching APIs (ReadDirectoryChangesW, FSEvents, inotify):

use notify::{Event, RecursiveMode, Watcher};
use std::sync::mpsc;

let (tx, rx) = mpsc::channel::<notify::Result<Event>>();
let mut watcher = notify::recommended_watcher(tx)?;
watcher.watch(std::path::Path::new("assets"), RecursiveMode::Recursive)?;

// Once per frame:
for event in rx.try_iter().flatten() {
    if event.kind.is_modify() {
        for path in event.paths {
            assets.reload_path(&path);    // re-run the loader, replace the slot
        }
    }
}

Because the rest of the engine holds handles, not references, replacing the slot's contents is invisible to users: the next get returns the new data. Editors save files in several steps (write a temp file, rename), so debounce: collect changed paths for a few hundred milliseconds before reloading. The notify-debouncer-full crate does this.

Workspaces

An engine is several crates: the core, the renderer, the editor, tools, the game. A Cargo workspace builds them together with one Cargo.lock and one target/ directory, like a top-level CMakeLists.txt with add_subdirectory for each component:

# Cargo.toml at the repository root
[workspace]
resolver = "3"
members = ["crates/*", "game", "tools/asset-cooker"]

[workspace.package]
edition = "2024"
license = "MIT OR Apache-2.0"

[workspace.dependencies]          # one version of each dependency, chosen here
glam = { version = "0.30", features = ["bytemuck"] }
wgpu = "27"
serde = { version = "1", features = ["derive"] }

[workspace.lints.clippy]
undocumented_unsafe_blocks = "warn"

[profile.dev.package."*"]
opt-level = 2                     # optimize dependencies even in debug builds
# crates/renderer/Cargo.toml
[package]
name = "engine-renderer"
version = "0.1.0"
edition.workspace = true

[dependencies]
engine-core = { path = "../core" }
glam.workspace = true
wgpu.workspace = true

[lints]
workspace = true

The [profile.dev.package."*"] setting deserves attention: it compiles all dependencies with optimizations while your own crates stay in fast-to-compile debug mode. A debug build of a game that uses an unoptimized math library or image decoder can be unplayably slow; this fixes it, at the cost of a longer first build.

Splitting into crates also speeds up incremental builds: Rust compiles a crate as a unit, so changing the game crate does not recompile the renderer. Keep crates focused enough that a typical change touches one or two.

Summary

C++Rust
add_custom_command in CMakebuild.rs writing to OUT_DIR
Dependency tracking for generated filescargo::rerun-if-changed
xxd -i, #embedinclude_bytes!, include_str!
Reflection macros / codegen for serialization#[derive(Serialize, Deserialize)]
Custom JSON/XML parsersserde + serde_json, ron, toml, bincode
mmap + cast for binary assetsbytemuck, rkyv
Asset manager with handlesSame design; Send bound checked at compile time
ReadDirectoryChangesW / inotifynotify
Top-level CMakeLists.txt + add_subdirectoryCargo workspace

Exercises

  1. Write a build.rs that sets cargo::rustc-env=BUILD_TIME=... (any string) and print it from main with env!("BUILD_TIME"). When does Cargo rerun the script?
  2. Add a reload(&mut self, h: Handle<T>) method to Assets that starts loading the same path again but keeps serving the old value until the new one arrives. What must Slot look like now?
  3. Give Texture an Rc<String> field and try to compile the asset example. Read the error. Which bound is violated, and why does the compiler care?

Hot reloading and plugins

C++ engines reload game code by building it as a DLL, unloading the old one and loading the new one while the process keeps running (Handmade Hero, Live++, Unreal's Live Coding). Plugins work the same way, with a C or C++ interface that both sides agree on. Rust can do all of this, but there is one fact to understand first: Rust has no stable ABI. This chapter explains what that means, then shows the practical ways to reload code, load plugins and embed a scripting language.

This chapter covers:

  • what "no stable ABI" means, and the C ABI escape hatch,
  • loading dynamic libraries with libloading,
  • hot reloading game code, and keeping state across reloads,
  • the hot-reload tools available today,
  • scripting with Lua, Rhai and WebAssembly.

No stable ABI

The layout of a default Rust struct, the calling convention of a Rust function, the layout of Vec, String and trait objects, and the mangling of symbol names can all change between compiler versions, and even between two builds with different flags. Rust makes no promise, and in practice field reordering means it really does change. C++ is in a similar position in theory (the ABI belongs to the compiler, not the standard) but in practice compilers keep it stable for years.

The consequences:

  • A Rust dynamic library and the program that loads it must be built by the same compiler, with the same flags, from the same dependency versions if they exchange Rust types. For hot reloading during development, that holds automatically: you are rebuilding the same workspace.
  • For plugins built separately (by users, by other teams, months later), the interface must use the C ABI: extern "C" functions and #[repr(C)] types, exactly as in the FFI chapter. Crates such as abi_stable and stabby generate stable-ABI versions of Vec, String, trait objects and more, so a plugin interface does not have to be written in raw C types.

Rust has two library crate types for this:

crate-typeProducesUse for
cdylib.dll / .so / .dylib exporting a C ABI, with the Rust standard library linked inPlugins, and libraries called from C, C++, Python
dylibA Rust dynamic library for other Rust codeRarely used directly; tooling for faster linking

Loading a library

The libloading crate wraps LoadLibrary / dlopen and GetProcAddress / dlsym. A minimal plugin:

# plugin/Cargo.toml
[lib]
crate-type = ["cdylib"]
// plugin/src/lib.rs
#[repr(C)]
pub struct PluginInfo {
    pub api_version: u32,
    pub name: *const std::ffi::c_char,
}

#[unsafe(no_mangle)]
pub extern "C" fn plugin_info() -> PluginInfo {
    PluginInfo { api_version: 1, name: c"sky-renderer".as_ptr() }
}

#[unsafe(no_mangle)]
pub extern "C" fn plugin_update(dt: f32) {
    // ...
}

#[unsafe(no_mangle)] keeps the symbol name as written (extern "C" alone does not); the unsafe(...) wrapper, new in the 2024 edition, marks that two libraries exporting the same name is your responsibility. The host:

use libloading::{Library, Symbol};

type InfoFn = unsafe extern "C" fn() -> PluginInfo;
type UpdateFn = unsafe extern "C" fn(f32);

// SAFETY: loading a library runs its initializers; we trust plugins/ to contain our plugins.
let lib = unsafe { Library::new("plugins/libsky.so")? };
let info: Symbol<InfoFn> = unsafe { lib.get(b"plugin_info")? };
let info = unsafe { info() };
if info.api_version != 1 {
    return Err("incompatible plugin".into());
}
let update: Symbol<UpdateFn> = unsafe { lib.get(b"plugin_update")? };
unsafe { update(0.016) };

Two lifetime details make this safer than the C++ equivalent:

  • Symbol<'lib, T> borrows the Library. You cannot unload the library (drop(lib)) while a Symbol from it is still alive: that is a compile error, not a crash in code that no longer exists.
  • But a plain function pointer copied out of a symbol, or a &'static str pointing into the library's data, escapes that check. Before unloading, make sure nothing from the library is still referenced: no function pointers, no trait objects whose vtables live in it, no threads running its code, no 'static data from it.

Hot reloading game code

The classic setup splits the program into a small host that owns the window, the memory and the main loop, and a game library that contains the logic. On each frame, the host checks whether the library changed and reloads it. The key design rule is the same as in C++: the state lives in the host; the library only contains functions. Then reloading swaps the code and keeps the world.

The runnable example below simulates this with function pointers instead of a real library, but the structure is the one you would use:

// Shared between host and game library: #[repr(C)] so both builds agree on it.
#[repr(C)]
#[derive(Debug, Default)]
pub struct GameState {
    pub frame: u64,
    pub player_x: f32,
    pub score: u32,
}

// The game library's interface: plain C-ABI function pointers.
#[repr(C)]
pub struct GameApi {
    pub update: extern "C" fn(state: &mut GameState, dt: f32),
}

// --- Version 1 of the game library ---
extern "C" fn update_v1(state: &mut GameState, dt: f32) {
    state.frame += 1;
    state.player_x += 1.0 * dt * 60.0;
}

// --- Version 2, after you edit and rebuild: the player is faster and scores ---
extern "C" fn update_v2(state: &mut GameState, dt: f32) {
    state.frame += 1;
    state.player_x += 3.0 * dt * 60.0;
    state.score += 10;
}

fn main() {
    let mut state = GameState::default();           // owned by the host: survives reloads
    let mut api = GameApi { update: update_v1 };    // in reality: loaded from game.dll

    for frame in 0..6 {
        if frame == 3 {
            println!("-- library changed on disk: reloading --");
            api = GameApi { update: update_v2 };    // unload old library, load new one
        }
        (api.update)(&mut state, 1.0 / 60.0);
        println!("{state:?}");
    }
}

With a real library, the reload step is:

  1. Copy game.dll to a temporary name and load the copy, so the compiler can overwrite the original while it is loaded (Windows locks loaded DLLs).
  2. Look up the GameApi (one exported function returning the table).
  3. Drop the old Library after the new one is loaded.

Things that break across a reload, and how to avoid them:

  • Changing the layout of GameState. The new code would interpret the old bytes differently. Either restart when the state struct changes, or serialize the state with serde before unloading and deserialize after, which also lets you add fields.
  • Heap data allocated by the old library. With Rust's default global allocator, every cdylib uses the system allocator, so a Vec allocated in the library and freed in the host works in practice. But a Vec's layout is not guaranteed to match across builds; prefer to keep heap-owning types in the host, or use the same compiler for both, which is the normal case in development.
  • Statics and thread-locals in the library are reset on reload. Keep state in GameState.
  • Trait objects and closures whose code lives in the library dangle after unloading. Do not store them in the host.

Hot-reload tools

You rarely need to write the loader by hand:

ToolHow it works
hot-lib-reloaderGenerates the libloading code from an attribute on a module: you mark functions as hot-reloadable, and calls go through the latest library. Uses Rust ABI, so same compiler on both sides.
subsecond (from the Dioxus project)Patches individual functions in a running binary, like Live++, without splitting into a library. Wrap the frame call in subsecond::call(...); changed functions are swapped in. Requires its CLI (dx) to drive the build.
Bevy's hot reloadingAssets and shaders reload out of the box; code hot patching is built on subsecond.

For assets and shaders, which change much more often than code, reload data instead (Assets). It needs no unsafe code and works on every platform.

Scripting

Many engines put gameplay logic in a scripting language, for fast iteration and for modders. The usual choices all have good Rust embeddings:

LanguageCrateNotes
Lua / LuaJIT / LuaumluaMature; safe API; Rust structs exposed as userdata; async support
RhairhaiPure-Rust scripting language with Rust-like syntax; easy to embed and sandbox
WebAssemblywasmtime, wasmerSandboxed, fast, any source language (Rust, C, C++, AssemblyScript); good for untrusted mods
JavaScriptrquickjs, boaFor UI or tooling scripts

A taste of mlua, exposing an engine function to Lua:

use mlua::Lua;

let lua = Lua::new();
let spawn = lua.create_function(|_, (kind, x, y): (String, f32, f32)| {
    println!("spawn {kind} at ({x}, {y})");
    Ok(())
})?;
lua.globals().set("spawn", spawn)?;

lua.load(r#"
    for i = 1, 3 do
        spawn("crate", i * 2.0, 0.0)
    end
"#).exec()?;

Argument conversion is generated from the Rust types ((String, f32, f32)), and a wrong type in the script becomes a Lua error, not a crash. Compared with writing Lua bindings in C++ by hand (or with sol2), there is less glue and the borrow checker prevents a script callback from holding a Rust reference beyond its call.

WebAssembly is worth a closer look for mods: each mod runs in a sandbox with its own memory, can only call the functions you give it, and can be compiled from Rust with the same toolchain as the engine. Fuel metering in wasmtime lets you cap how many instructions a script runs per frame.

Summary

C++Rust
ABI de facto stable per compilerNo stable Rust ABI; extern "C" + #[repr(C)] for plugins
extern "C" __declspec(dllexport)#[unsafe(no_mangle)] pub extern "C" fn in a cdylib
LoadLibrary / dlopenlibloading::Library::new
GetProcAddress / dlsymlib.get::<fn type>(b"name"), borrows the library
Handmade-style DLL reloadHost owns state; library exposes a function table
Live++subsecond
sol2 / LuaBridgemlua
Custom VM / mod sandboxwasmtime

Exercises

  1. Add a render function pointer to GameApi that prints the player position, and a version 3 that renders differently. Reload twice.
  2. Add a field to GameState in version 2 only. Why would that be a problem with a real library? Sketch how you would carry the state across with serde.
  3. Build a real cdylib with one extern "C" fn add(a: i32, b: i32) -> i32, load it with libloading from a separate binary, and call it. Then try to drop(lib) while you still hold the Symbol. What does the compiler say?

Case study: a small renderer

This last chapter puts the book together in one program. It is a complete, runnable miniature engine: math types, an asset store with typed handles, a struct-of-arrays world with a system, a renderer behind a trait, and a fixed timestep loop. To run anywhere (including the Playground) it renders with a small software rasterizer into a grid of characters. The second half of the chapter shows how to replace that back end with wgpu and a real window, and what a full project layout looks like.

This chapter covers:

  • the complete program, and which chapter each part comes from,
  • design decisions: what owns what, and who borrows what when,
  • replacing the back end with wgpu,
  • the project layout of a real engine, and where to go next.

The whole program

Press Run. Then change a spin rate or a scale, or add an entity, and run it again.

use std::marker::PhantomData;
use std::ops::{Add, Mul, Sub};

// ---------- math (Math and SIMD) ----------
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Vec2 { x: f32, y: f32 }
impl Vec2 {
    const fn new(x: f32, y: f32) -> Self { Vec2 { x, y } }
    fn rotate(self, angle: f32) -> Self {
        let (s, c) = angle.sin_cos();
        Vec2::new(self.x * c - self.y * s, self.x * s + self.y * c)
    }
    fn cross(self, o: Vec2) -> f32 { self.x * o.y - self.y * o.x }
}
impl Add for Vec2 { type Output = Vec2; fn add(self, o: Vec2) -> Vec2 { Vec2::new(self.x + o.x, self.y + o.y) } }
impl Sub for Vec2 { type Output = Vec2; fn sub(self, o: Vec2) -> Vec2 { Vec2::new(self.x - o.x, self.y - o.y) } }
impl Mul<f32> for Vec2 { type Output = Vec2; fn mul(self, s: f32) -> Vec2 { Vec2::new(self.x * s, self.y * s) } }

// ---------- assets (Handles and arenas, Assets) ----------
struct Mesh { triangles: Vec<[Vec2; 3]> }

struct Handle<T> { index: u32, _t: PhantomData<fn() -> T> }
impl<T> Clone for Handle<T> { fn clone(&self) -> Self { *self } }
impl<T> Copy for Handle<T> {}

struct Assets<T> { items: Vec<T> }
impl<T> Assets<T> {
    fn new() -> Self { Assets { items: Vec::new() } }
    fn add(&mut self, item: T) -> Handle<T> {
        self.items.push(item);
        Handle { index: self.items.len() as u32 - 1, _t: PhantomData }
    }
    fn get(&self, h: Handle<T>) -> &T { &self.items[h.index as usize] }
}

// ---------- world (ECS) ----------
#[derive(Clone, Copy)]
struct Transform { position: Vec2, rotation: f32, scale: f32, }

#[derive(Default)]
struct World {
    transforms: Vec<Transform>,
    meshes: Vec<Option<Handle<Mesh>>>,
    spins: Vec<Option<f32>>,          // radians per second
    glyphs: Vec<char>,
}
impl World {
    fn spawn(&mut self, t: Transform, mesh: Option<Handle<Mesh>>, spin: Option<f32>, glyph: char) -> usize {
        self.transforms.push(t);
        self.meshes.push(mesh);
        self.spins.push(spin);
        self.glyphs.push(glyph);
        self.transforms.len() - 1
    }
}

// A system: borrows exactly the columns it needs.
fn spin_system(transforms: &mut [Transform], spins: &[Option<f32>], dt: f32) {
    for (t, spin) in transforms.iter_mut().zip(spins) {
        if let Some(rate) = spin {
            t.rotation += rate * dt;
        }
    }
}

// ---------- rendering (OpenGL / Vulkan / wgpu) ----------
trait Renderer {
    fn begin_frame(&mut self);
    fn draw(&mut self, mesh: &Mesh, transform: &Transform, glyph: char);
    fn end_frame(&mut self) -> String;
}

/// A software rasterizer into a character grid. A wgpu backend would
/// implement the same trait with buffers, a pipeline and a render pass.
struct AsciiRenderer { width: usize, height: usize, pixels: Vec<char> }

impl AsciiRenderer {
    fn new(width: usize, height: usize) -> Self {
        AsciiRenderer { width, height, pixels: vec![' '; width * height] }
    }
    fn to_screen(&self, p: Vec2) -> Vec2 {
        // World y in [-1, 1] spans the grid's height. A character cell is about twice
        // as tall as it is wide, so one world unit in x is twice as many columns.
        let half_h = self.height as f32 * 0.5;
        Vec2::new(self.width as f32 * 0.5 + p.x * half_h * 2.0, half_h - p.y * half_h)
    }
}

impl Renderer for AsciiRenderer {
    fn begin_frame(&mut self) {
        self.pixels.fill('.');
    }
    fn draw(&mut self, mesh: &Mesh, t: &Transform, glyph: char) {
        for tri in &mesh.triangles {
            let [a, b, c] = tri.map(|v| self.to_screen((v * t.scale).rotate(t.rotation) + t.position));
            let area = (b - a).cross(c - a);
            if area.abs() < f32::EPSILON { continue; }
            // Bounding box, clamped to the screen: the indexing below can never go out of range.
            let min_x = a.x.min(b.x).min(c.x).floor().max(0.0) as usize;
            let max_x = (a.x.max(b.x).max(c.x).ceil() as usize).min(self.width);
            let min_y = a.y.min(b.y).min(c.y).floor().max(0.0) as usize;
            let max_y = (a.y.max(b.y).max(c.y).ceil() as usize).min(self.height);
            for y in min_y..max_y {
                for x in min_x..max_x {
                    let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
                    // Edge functions, normalized by the triangle's winding.
                    let w0 = (c - b).cross(p - b) / area;
                    let w1 = (a - c).cross(p - c) / area;
                    let w2 = (b - a).cross(p - a) / area;
                    if w0 >= 0.0 && w1 >= 0.0 && w2 >= 0.0 {
                        self.pixels[y * self.width + x] = glyph;
                    }
                }
            }
        }
    }
    fn end_frame(&mut self) -> String {
        self.pixels.chunks(self.width).map(|row| row.iter().collect::<String>() + "\n").collect()
    }
}

fn render_world(world: &World, assets: &Assets<Mesh>, renderer: &mut dyn Renderer) -> String {
    renderer.begin_frame();
    for ((t, mesh), glyph) in world.transforms.iter().zip(&world.meshes).zip(&world.glyphs) {
        if let Some(handle) = mesh {
            renderer.draw(assets.get(*handle), t, *glyph);
        }
    }
    renderer.end_frame()
}

// ---------- the loop (Game loop) ----------
fn main() {
    let mut meshes = Assets::new();
    let quad = meshes.add(Mesh {
        triangles: vec![
            [Vec2::new(-1.0, -1.0), Vec2::new(1.0, -1.0), Vec2::new(1.0, 1.0)],
            [Vec2::new(-1.0, -1.0), Vec2::new(1.0, 1.0), Vec2::new(-1.0, 1.0)],
        ],
    });
    let tri = meshes.add(Mesh {
        triangles: vec![[Vec2::new(0.0, 1.0), Vec2::new(-0.87, -0.5), Vec2::new(0.87, -0.5)]],
    });

    let mut world = World::default();
    world.spawn(Transform { position: Vec2::new(-0.8, 0.0), rotation: 0.0, scale: 0.45 }, Some(quad), Some(1.0), '#');
    world.spawn(Transform { position: Vec2::new(0.8, -0.1), rotation: 0.0, scale: 0.7 }, Some(tri), Some(-0.5), '@');
    world.spawn(Transform { position: Vec2::new(0.0, 0.0), rotation: 0.0, scale: 1.0 }, None, None, '?'); // no mesh: not drawn

    let mut renderer = AsciiRenderer::new(64, 20);
    let step = 1.0 / 60.0;
    for _frame in 0..30 {                     // half a second of fixed steps
        spin_system(&mut world.transforms, &world.spins, step);
    }
    print!("{}", render_world(&world, &meshes, &mut renderer));
}

Reading it as a map of the book

Part of the programIdeaChapter
Vec2 with Add, Sub, Mul<f32>Copy value types, operator traitsOperators, Math
Handle<T> with PhantomData<fn() -> T>Typed handles instead of pointersHandles and arenas
Assets<T> owns every MeshOne owner per resourceOwnership, Assets
World with one Vec per componentStruct of arrays, entities as indicesECS, Memory and performance
spin_system(&mut [Transform], &[Option<f32>], dt)Split borrows; access visible in the signatureBorrowing, ECS
trait Renderer, &mut dyn RendererDynamic dispatch where it is cheap (once per draw)Traits and generics
tri.map(...), zip, chunksIterators with no bounds checks in the hot loopClosures and iterators
Clamped bounding box before indexingSafe indexing that cannot panicMemory and performance
if let Some(handle) = meshAbsence is a type, not a null pointerEnums and match
Fixed step, update before renderFixed timestepGame loop

The program has no unsafe, no Rc, no RefCell and no global state, and it did not need them. Note also what it does not contain: no "manager" objects holding pointers to each other. Data flows down from main by borrowing:

main
 ├── owns  Assets<Mesh>  ── lends &Assets ──────────┐
 ├── owns  World          ── lends &mut columns ─► spin_system
 │                        └─ lends &World ─────────► render_world ──► renderer.draw(&Mesh, &Transform)
 └── owns  AsciiRenderer  ── lends &mut dyn Renderer ┘

Each frame, spin_system gets exclusive access to transforms; then render_world gets shared access to the world and the assets and exclusive access to the renderer. The borrow checker verifies that these phases do not overlap. If you later run systems in parallel, the same signatures tell you which ones can run together.

Replacing the back end with wgpu

The Renderer trait is the seam between the engine and the GPU. A wgpu back end implements the same three methods, using what the wgpu chapter introduced. The essential parts:

struct GpuMesh { vertices: wgpu::Buffer, count: u32 }

struct WgpuRenderer {
    device: wgpu::Device,
    queue: wgpu::Queue,
    surface: wgpu::Surface<'static>,
    pipeline: wgpu::RenderPipeline,
    instances: wgpu::Buffer,             // per-draw transforms, rewritten each frame
    gpu_meshes: Vec<GpuMesh>,            // indexed like Assets<Mesh>
    pending: Vec<(u32, Instance)>,       // draws collected between begin and end
}

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Instance { position: [f32; 2], rotation: f32, scale: f32, color: [f32; 4] }

impl WgpuRenderer {
    fn draw_frame(&mut self) -> Result<(), wgpu::SurfaceError> {
        let frame = self.surface.get_current_texture()?;
        let view = frame.texture.create_view(&Default::default());
        let instances: Vec<Instance> = self.pending.iter().map(|(_, i)| *i).collect();
        self.queue.write_buffer(&self.instances, 0, bytemuck::cast_slice(&instances));

        let mut encoder = self.device.create_command_encoder(&Default::default());
        {
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &view,
                    resolve_target: None,
                    ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store },
                    depth_slice: None,
                })],
                ..Default::default()
            });
            pass.set_pipeline(&self.pipeline);
            pass.set_vertex_buffer(1, self.instances.slice(..));
            for (i, (mesh, _)) in self.pending.iter().enumerate() {
                let gpu = &self.gpu_meshes[*mesh as usize];
                pass.set_vertex_buffer(0, gpu.vertices.slice(..));
                pass.draw(0..gpu.count, i as u32..i as u32 + 1);
            }
        }
        self.queue.submit([encoder.finish()]);
        frame.present();
        self.pending.clear();
        Ok(())
    }
}

And the loop moves into winit's ApplicationHandler (Game loop): RedrawRequested runs the fixed-step systems for the elapsed time, calls render_world, and requests the next redraw. Nothing in World, Assets or the systems changes. That is the payoff of the ownership-first design: the engine core is plain data and functions, and the platform layer is a thin shell around it.

Some decisions you would make next, and where the book discusses them:

  • Generations in handles, so meshes can be unloaded: Handles and arenas.
  • Despawning entities: generational entity IDs, or move to hecs or bevy_ecs: ECS.
  • Uploading meshes in the background: the asset cache with a channel: Assets.
  • Hot-reloading shaders: load WGSL from disk in debug builds and rebuild the pipeline: wgpu, Hot reloading.
  • Instancing and batching: sort pending by mesh and issue one draw per mesh with an instance range.
  • Parallel systems: split borrows with std::thread::scope, or rayon's par_iter_mut on component columns: Concurrency.

A real project layout

my-engine/
├── Cargo.toml                 # [workspace], shared dependencies and lints
├── crates/
│   ├── core/                  # math re-exports, handles, time, logging setup
│   ├── ecs/                   # or depend on hecs / bevy_ecs instead
│   ├── assets/                # loaders, cache, file watching
│   ├── render/                # Renderer trait + wgpu back end, shaders/
│   │   ├── build.rs           # compile or validate shaders
│   │   └── shaders/*.wgsl
│   └── platform/              # winit app, input mapping
├── game/                      # the actual game: systems and content, binary crate
├── tools/
│   └── asset-cooker/          # offline processing: textures, meshes
├── assets/                    # source data (RON, glTF, KTX2)
└── .github/workflows/ci.yml   # fmt, clippy, test

Each crate depends only on the ones below it. The renderer does not know about the game; the game knows the renderer only through core types and the Renderer API. Cargo enforces the dependency direction: a cycle between crates does not build.

Where to go from here

  • Read the source of a real engine. Bevy is large, modular and well documented; Fyrox is a more classic editor-centric engine; macroquad is a small, immediate-mode framework that is pleasant to read in an afternoon.
  • Port a small piece of your own C++ code: a math library, an allocator, a file format parser. Run Clippy on the result and read every suggestion.
  • When something fights the borrow checker, try restructuring the data before reaching for Rc<RefCell<...>> or unsafe. The book's cheat sheet collects the usual translations.

Exercises

  1. Add a Velocity column and a movement_system, and make the triangle drift across the screen. Which existing function signatures change?
  2. Add a second renderer, CountingRenderer, that only counts triangles and returns "N triangles" from end_frame. Render the same world with both, without changing render_world.
  3. Make render_world generic (renderer: &mut impl Renderer) instead of taking &mut dyn Renderer. What changes in the compiled program, and does it matter here?

C++ to Rust cheat sheet

A quick reference: the C++ thing you reach for, its usual Rust spelling, and the chapter that explains it. When the translation is not one-to-one, the chapter is worth reading before you rely on the table.

Values and types

C++RustChapter
const auto x = 1; / auto x = 1;let x = 1; / let mut x = 1;Values and types
int, int64_t, size_t, uint8_ti32, i64, usize, u8Values and types
Implicit numeric conversionsNone: as, From, TryFromValues and types
Signed overflow is UBPanic in debug, wrap in release; wrapping_*, checked_*, saturating_*Values and types
std::array<T, N>[T; N]Values and types
std::pair, std::tuple(A, B)Values and types
struct with constructorstruct + fn new(...) -> SelfValues and types
constexpr value / functionconst / const fnValues and types
static_assert(cond)const _: () = assert!(cond);Macros
cond ? a : bif cond { a } else { b }Values and types
enum classenumEnums and match
std::variant + std::visitenum with data + matchEnums and match
std::optional<T>, nullable T*Option<T>, Option<&T>Enums and match
switchmatch (exhaustive, no fall-through)Enums and match
Structured bindingsPatterns: let (a, b) = ...;, if let, let ... elseEnums and match

Ownership and references

C++RustChapter
RAII, destructorDropOwnership
auto y = std::move(x);let y = x; (and x is unusable)Ownership
Copy constructor.clone() (Clone); implicit only for Copy typesOwnership
Rule of fiveNothing to write; add Drop if neededOwnership
const T&&T (many at once)Borrowing
T&&mut T (exclusive)Borrowing
std::span<T>, std::string_view&[T], &strBorrowing
__restrictEvery &mut TBorrowing
Iterator invalidation (UB)Compile errorBorrowing
Dangling reference (UB)Compile error; lifetimesLifetimes
Class holding a string_viewstruct View<'a> { s: &'a str }Lifetimes
std::unique_ptr<T>Box<T>Smart pointers
std::shared_ptr<T>Rc<T> (one thread), Arc<T> (atomic)Smart pointers
std::weak_ptr<T>Weak<T>, .upgrade()Smart pointers
mutable memberCell<T>, RefCell<T>Smart pointers
Object pool + raw pointersArena + generational Handle<T>Handles and arenas

Classes, templates and operators

C++RustChapter
Member function / const member functionfn f(&mut self) / fn f(&self)Borrowing
Abstract base class, virtual functionsTrait, dyn TraitTraits and generics
Template + conceptGeneric with trait boundsTraits and generics
auto f() returning a hidden typefn f() -> impl TraitTraits and generics
Nested typedef in a traits classAssociated typeTraits and generics
Inheritance of dataComposition (+ traits for behavior)Traits and generics
operator+, operator+=impl Add, impl AddAssignOperators
operator[]Index, IndexMutOperators
operator==, operator<=>#[derive(PartialEq, Eq, PartialOrd, Ord)]Operators
Converting constructorFrom / IntoOperators
operator<<(ostream&, T)impl Display, #[derive(Debug)]Operators
operator-> on a smart pointerDerefOperators
LambdaClosure (move for by-value capture)Closures and iterators
std::function<R(A)>Box<dyn Fn(A) -> R>Closures and iterators
Callable template parameterimpl Fn(A) -> R, F: FnMut(A) -> RClosures and iterators

Errors

C++RustChapter
ExceptionsResult<T, E> and ?Errors
std::expected<T, E>Result<T, E>Errors
[[nodiscard]]#[must_use] (default on Result)Errors
assert, std::terminateassert!, panic!, .expect("why")Errors
Exception class hierarchyError enum with thiserrorErrors
Catch-all handler at the topanyhow::Result with .context(...)Errors
-fno-exceptionspanic = "abort"Errors

Standard library

C++RustChapter
std::vector<T>Vec<T>Collections
v.at(i) / v[i]v.get(i) (Option) / v[i] (checked)Collections
Erase-remove idiomv.retain(keep) (keep is a closure)Collections
std::unordered_map, std::mapHashMap, BTreeMapCollections
map[key] (inserting)map.entry(key).or_default()Collections
std::stringString (always UTF-8)Collections
std::filesystem::pathPathBuf, &PathCollections
<algorithm>, rangesIterator adapters: map, filter, zip, fold, collectClosures and iterators
std::threadstd::thread::spawn, std::thread::scopeConcurrency
std::mutex next to the dataMutex<T> containing the dataConcurrency
std::atomic<T>AtomicU32 etc. with OrderingConcurrency
Thread pool / TBB parallel_forrayon: par_iter()Concurrency
std::chrono::steady_clockstd::time::Instant, DurationGame loop
Function-local staticOnceLock, LazyLockGame loop

Build, modules and tooling

C++RustChapter
CMake + vcpkg/ConanCargo + crates.ioCargo
Debug / Releasecargo build / cargo build --release (profiles)Cargo
add_subdirectoryWorkspace membersAssets and build
add_custom_commandbuild.rsAssets and build
namespacemodModules
#include "x.h"mod x; + useModules
public / privatepub / private by defaultModules
#ifdef#[cfg(...)], Cargo featuresMacros
#define macrosmacro_rules!Macros
Reflection macros, code generators#[derive(...)]Macros
GoogleTest / Catch2#[test], cargo testTesting
Google BenchmarkcriterionTesting
clang-format / clang-tidycargo fmt / cargo clippyTesting
Doxygencargo doc (examples are tested)Testing

Low level

C++RustChapter
sizeof, alignof, offsetofsize_of::<T>(), align_of::<T>(), offset_of!Memory and performance
Declaration-order layout#[repr(C)]Memory and performance
alignas(64)#[repr(align(64))]Memory and performance
Replace operator new#[global_allocator]Memory and performance
Arena / linear allocatorbumpaloHandles and arenas
T**const T, *mut T (deref in unsafe)Unsafe
Uninitialized storageMaybeUninit<T>Unsafe
reinterpret_castPointer as casts; bytemuck for safe byte viewsUnsafe
ASan / UBSanMiriUnsafe
extern "C" declarationsunsafe extern "C" { ... }FFI
Exporting a C API#[unsafe(no_mangle)] pub extern "C" fnFFI
char* stringsCStr, CString, c"..."FFI
Headers → bindingsbindgen; cbindgen for the reverseFFI
<immintrin.h>std::arch + #[target_feature]Math and SIMD
LoadLibrary / dlopenlibloadingHot reloading

Graphics and engine

C++RustChapter
GLM / DirectXMathglamMath and SIMD
memcpy a struct into a GPU bufferbytemuck::cast_slice on #[derive(Pod)] typesMath and SIMD
GLFW / SDLwinit (ApplicationHandler)Game loop
glad / GLEWgl, glowOpenGL
vulkan.h / volkashVulkan
VMAgpu-allocator, vk-memVulkan
Dawn, bgfx, sokol_gfxwgpuwgpu
openxr.h, OpenXR-Hppopenxr-sys, openxrOpenXR
glslc / dxcnaga, shaderc, from build.rswgpu
EnTT, flecshecs, bevy_ecsECS
SingletonsContext passed as a parameter; ECS resourcesGame loop
Custom serialization / reflectionserdeAssets and build
sol2 (Lua)mluaHot reloading

When the borrow checker says no

SymptomUsual fixChapter
"cannot borrow as mutable because it is also borrowed as immutable"Shorten the first borrow: copy the value out, or finish using it firstBorrowing
Pushing to a Vec while holding a reference into itHold an index instead of a referenceBorrowing
Two &mut into the same structBorrow separate fields (split borrows); destructure let S { a, b } = &mut s;ECS
Two &mut into the same slicesplit_at_mut, chunks_mut, iter_mutCollections
A struct wants to store a reference to another objectStore a handle or index; or own the dataHandles and arenas
Objects pointing at each other (graph, parent links)Arena + handles; Rc + Weak only if ownership is truly sharedECS
"borrowed value does not live long enough"Move the owner to an outer scope, or return an owned valueLifetimes
"Rc<...> cannot be sent between threads safely"Arc (and Mutex for mutation)Concurrency
A closure passed to thread::spawn borrows a localmove the data in, or use thread::scopeConcurrency
Global mutable statePass a context; or Mutex, atomics, OnceLockGame loop

Further reading

Contributing and translating

The source of this book lives at github.com/xw0/rust-for-cpp. Fixes, new examples and translations are welcome as pull requests.

License

  • Text and diagrams: CC BY 4.0.
  • Code (examples, scripts, styles): MIT.

If you reuse or adapt material, credit it as:

Rust for C++ Programmers (https://xw0.github.io/rust-for-cpp/), licensed under CC BY 4.0.

and say whether you changed it.

How translations work

English Markdown under src/ is the single source of truth. Each translation is a gettext catalog, po/<lang>.po, that maps every English paragraph, heading, list item and table cell to its translation. At build time the mdbook-i18n-helpers preprocessor swaps the translated text in. Code blocks are shared, so examples never drift between languages.

When an English paragraph changes, the old translation is marked fuzzy and the English text is shown until a translator updates it. A translation can therefore lag behind without ever breaking the build or showing outdated content as if it were current.

Interactive diagrams are written in English in theme/js/diagrams.js. Their strings are translated in theme/js/i18n-<lang>.js, a plain table from the English string to the translation; missing entries fall back to English.

Translating a chapter

# 1. Extract all English messages into po/messages.pot
MDBOOK_OUTPUT='{"xgettext": {"pot-file": "messages.pot"}}' mdbook build -d po

# 2. Create or update the catalog for your language
msginit -i po/messages.pot -l zh_CN -o po/zh-CN.po   # first time only
msgmerge --update po/zh-CN.po po/messages.pot        # afterwards

# 3. Edit po/zh-CN.po (Poedit, Lokalize, or any text editor), then preview
MDBOOK_BOOK__LANGUAGE=zh-CN mdbook serve -d book/zh-CN

Building locally

cargo install mdbook --version "^0.4" --locked
cargo install mdbook-i18n-helpers --locked
mdbook serve --open     # English
mdbook test             # compile and run every Rust example