Programming Languages
Rust from first install to ownership, traits, async and the crates used for web, CLI, games and embedded.
A path through Rust for developers who already know another language: syntax and data types, ownership and borrowing, error handling, traits and lifetimes, concurrency and async, then the ecosystem for web services, databases, CLIs, GUIs, games, embedded and WebAssembly. Each subject links the official documentation or the crate's own docs.
The subjects follow the roadmap.sh Rust roadmap.
Rust is a compiled systems language that gives you C-level control and speed while the compiler proves memory and thread safety at build time. Start by installing the toolchain with rustup, building a project with Cargo and getting an editor with rust-analyzer working.
A general-purpose language with no garbage collector: ownership and borrowing rules checked by the compiler decide when memory is freed. It compiles to native code through LLVM and has a rich type system with traits and enums.
You get predictable performance, no data races in safe code, fearless refactoring thanks to strict types, and excellent tooling (Cargo, clippy, rustfmt). The cost is a steeper learning curve and longer compile times.
Install through rustup, which manages toolchains (stable, beta, nightly) and targets. cargo new, cargo build, cargo run and cargo check are the everyday commands.
rust-analyzer is the language server behind VS Code, Neovim, Helix and Zed; RustRover is JetBrains' IDE. Add clippy and rustfmt components with rustup and pin a project's version with rust-toolchain.toml.
Rust has no official REPL; the browser Playground compiles snippets on stable, beta or nightly, can run clippy, show assembly or MIR, and share links. Useful for bug reports and quick experiments.
The syntax every Rust program uses: immutable-by-default bindings, expression-oriented control flow, functions and methods, and pattern matching. Scalar types are strictly sized and never converted implicitly, so casts are always written out.
let bindings are immutable unless marked mut, and shadowing lets you rebind a name with a new type. const values are inlined at compile time and need a type; static has one fixed address.
if is an expression that returns a value, loop can break with a value, and while/for iterate; for works over anything implementing IntoIterator. Labels like 'outer: break out of nested loops.
Functions declare parameter and return types, and the last expression without a semicolon is the return value. Methods take self, &self or &mut self, and associated functions like new are called with Type::new().
match must be exhaustive, so adding an enum variant breaks every match that forgot it. Patterns destructure structs, tuples and slices, bind with @, add guards with if, and appear in let, if let and let … else.
Signed i8–i128 and unsigned u8–u128, plus pointer-sized isize/usize used for indexing. Overflow panics in debug builds and wraps in release, so use checked_add, wrapping_add or saturating_add when it matters.
bool is true or false, one byte in size, and never converts implicitly from integers. && and || short-circuit; bool::then turns a condition into an Option.
f32 and f64 are IEEE 754 numbers. Because NaN != NaN, floats implement only PartialEq and PartialOrd, so sorting needs total_cmp and they cannot be HashMap keys directly.
char is a four-byte Unicode scalar value, not a byte. A String is not an array of chars; iterate with .chars() and remember one visible glyph can be several chars.
Rust has no classes. Data lives in structs and enums, behaviour is attached with impl blocks, and shared behaviour across types is expressed with traits. Combining these covers what inheritance does elsewhere, without its fragility.
Tagged unions: each variant can carry its own data, like Message::Move { x, y }. Together with match they model states that cannot be mixed up, and Option and Result are just enums from the standard library.
Named-field structs, tuple structs (handy for newtypes like struct Meters(f64)) and unit structs. Fields are private outside their module unless marked pub, and update syntax ..other copies the rest.
A set of methods a type promises to provide, optionally with default bodies. Standard traits like Debug, Clone, PartialEq, Display and Iterator plug your types into the language and library.
impl Type { … } adds inherent methods and associated functions; impl Trait for Type implements a trait. A type may have many impl blocks, but the orphan rule only lets you implement a trait if the trait or the type is local to your crate.
The compound types built into the language plus the collections in std::collections. Most code needs only Vec, String and HashMap; reach for the others when their specific complexity guarantees fit the problem.
A fixed-size group of values of different types, accessed with .0, .1 or destructured with let (a, b) = t. The empty tuple () is the unit type returned by functions with no value.
[T; N] has its length in the type and lives on the stack. Slices &[T] borrow a view of any contiguous run, so functions usually accept slices instead of arrays or vectors.
String is an owned, growable UTF-8 buffer; &str is a borrowed slice of one. You cannot index a string by integer because byte offsets may split a character; use .chars(), .bytes() or range slicing on char boundaries.
Vec<T> is the default growable list: heap-allocated, contiguous, amortised O(1) push. Pre-size with Vec::with_capacity, and prefer .get(i) over v[i] when an out-of-range index should not panic.
HashMap<K, V> with keys that implement Eq + Hash. The entry API (*map.entry(k).or_insert(0) += 1) avoids double lookups. The default SipHash hasher resists DoS but is slower than alternatives like ahash.
HashSet<T> is a HashMap with no values: O(1) membership tests plus union, intersection and difference. Iteration order is unspecified, so use BTreeSet when you need sorted output.
A doubly linked list in std. It is rarely the right choice in Rust because poor cache locality usually makes Vec or VecDeque faster; writing your own is a classic lesson in ownership pain.
Use VecDeque<T>, a ring buffer with O(1) push_back and pop_front, for FIFO queues and BFS. For queues between threads use channels instead.
There is no separate stack type: a Vec with push and pop is a LIFO stack, and last() peeks at the top.
BinaryHeap<T> is a max-heap priority queue with O(log n) push and pop. For a min-heap wrap items in std::cmp::Reverse.
The feature that makes Rust different: every value has one owner, it is dropped when the owner goes out of scope, and access by others happens through borrows the compiler checks. Once this model clicks, most borrow-checker errors read as helpful advice.
Each value has exactly one owner; assigning or passing it moves ownership unless the type is Copy. When the owner leaves scope, Drop runs, which rules out double frees and use-after-free in safe code.
You may have many &T shared references or exactly one &mut T, never both at once. Slices like &str and &[T] borrow part of a collection, so the data cannot be freed or resized while they live.
Fixed-size values live on the stack by default; Box, Vec and String keep a small header on the stack that points to heap data. Knowing which is which explains moves, Copy and why large arrays can overflow the stack.
Ordered collections and the smart pointers and synchronisation types you need once single ownership is not enough: shared ownership, heap indirection and data shared between threads.
An ordered map with O(log n) operations that iterates in key order and supports range queries. Keys need Ord rather than Hash, and output is deterministic, which helps tests.
The sorted counterpart of HashSet: unique values kept in order, with first, last and range for floor and ceiling style lookups.
Box<T> puts a value on the heap with a single owner. Use it for recursive types like trees, for large values you want to move cheaply, and for trait objects such as Box<dyn Error>.
Rc<T> gives shared ownership on one thread through reference counting; Rc::clone bumps the count. Combine with RefCell for mutation and use Weak to break cycles that would otherwise leak.
The thread-safe Rc: atomic reference counting so clones can move to other threads. It only shares; to mutate, wrap the inner value in a Mutex, RwLock or an atomic.
Mutex<T> owns the data it protects, so you cannot touch it without lock(), which returns a guard that unlocks on drop. A panic while holding the lock poisons it; keep critical sections short and never hold a std guard across .await.
Allows many readers or one writer at a time, which helps when reads dominate. Writer starvation and fairness depend on the operating system, so measure before swapping a Mutex for it.
std::sync::mpsc provides multi-producer, single-consumer channels: channel() is unbounded, sync_channel(n) applies backpressure. Sending moves ownership of the value, so no locking is needed.
Rust has no exceptions. Recoverable failures are values of type Result<T, E>, absent values are Option<T>, and panic! is reserved for bugs. The ? operator keeps the happy path readable while still forcing every error to be handled somewhere.
Option is Some(T) or None; Result is Ok(T) or Err(E). Combinators such as map, and_then, ok_or and unwrap_or_else transform them without nested matches; keep unwrap for tests and impossible cases.
? returns early with the error and converts it through From, so a function returning Result<T, MyError> can call APIs with different error types. It also works on Option inside functions returning Option.
Libraries usually define an error enum that implements std::error::Error and Display, often generated with thiserror. Applications often use anyhow to collect any error and attach context.
A crate is one compilation unit, a library or a binary; a package is the Cargo.toml that builds one or more crates; modules organise code and privacy inside a crate. Cargo resolves dependencies from crates.io and records exact versions in Cargo.lock.
mod declares modules, either inline or in foo.rs / foo/mod.rs. Items are private by default; pub, pub(crate) and pub(super) widen visibility, and use plus pub use shape the public API.
Dependencies use SemVer requirements, so serde = "1.0" accepts any compatible 1.x. Features toggle optional code, workspaces share one lockfile across crates, and cargo update and cargo tree show what is resolved.
Add metadata (license, description, repository), log in with cargo login, then cargo publish. Published versions are permanent; cargo yank only stops new projects from picking a broken version.
Testing is built into the language and Cargo: annotate functions with #[test] and run cargo test. Unit tests live next to the code, integration tests in tests/, and code examples in doc comments run as tests too.
Unit tests sit in a #[cfg(test)] mod tests block and can reach private items; integration tests in tests/ see only the public API. Use assert_eq!, #[should_panic] and tests that return Result.
Mock dependencies by hiding them behind traits; mockall can generate mock types. proptest and quickcheck generate random inputs, check that invariants hold and shrink failures to a minimal case.
The Send and Sync traits let the compiler reject data races, so threaded code that compiles is free of them. Choose OS threads for CPU-bound work (or rayon for data parallelism) and async for many concurrent I/O-bound tasks.
thread::spawn takes a move closure and returns a JoinHandle; thread::scope lets threads borrow local data safely. Channels move values between threads so ownership, not locks, prevents sharing.
AtomicUsize, AtomicBool and friends do lock-free updates with an explicit Ordering. Relaxed suits counters, Acquire/Release pairs publish data between threads, and SeqCst is the safe default when unsure.
An async fn returns a Future, a state machine that does nothing until polled. .await yields to the executor, which the standard library does not provide; a runtime such as Tokio drives the futures.
Generics let one function or type work for many types, and trait bounds say what those types must be able to do. They are monomorphised into specialised code with no runtime cost, while dyn Trait gives dynamic dispatch when you need mixed types in one collection.
Declare required methods and defaults, then impl Trait for Type. #[derive(...)] generates common ones; blanket impls like impl<T: Display> ToString for T cover every matching type at once.
Bounds appear as T: Clone + Debug, in where clauses or as impl Trait arguments. Associated types such as Iterator::Item fix one output type per implementation, unlike generic parameters that allow many.
Const generics ([T; N] with const N: usize), PhantomData markers and the typestate pattern encode rules in types, so invalid states fail to compile. Watch compile times and binary size as monomorphisation multiplies code.
Lifetimes name how long a reference stays valid so the borrow checker can prove no reference outlives its data. You rarely write them in function bodies; they appear in signatures and structs that hold references.
Writing <'a> on a function and tying parameters and the return type to it tells the compiler the returned reference cannot outlive the shorter-lived input. Structs that hold references need a lifetime parameter, and 'static means valid for the whole program.
Three rules let you skip annotations: each input reference gets its own lifetime, a single input lifetime flows to all outputs, and with &self the output borrows from self. Anything else must be written out.
Variance decides when a longer lifetime may stand in for a shorter one. &'a T is covariant, &mut T is invariant in T, and function arguments are contravariant; this explains surprising errors with &mut and generic wrappers.
Macros generate code at compile time from tokens, which is how println!, vec! and #[derive(Serialize)] work. Reach for them when functions and generics cannot express the repetition, because they are harder to read and debug.
Pattern-based macros that match token trees with fragments like $e:expr and repeat with $(...),*. They are hygienic for local variables, and #[macro_export] makes them usable from other crates.
Rust functions in a dedicated proc-macro crate that transform a TokenStream: derive, attribute and function-like macros. Most use syn to parse and quote to emit code.
Macros can accept syntax that is not Rust at all, such as HTML templates in view! or SQL checked at compile time in sqlx::query!. Keep the grammar small and produce clear errors with compile_error! or spans.
Rust web servers are fast, small and safe, and most are built on Tokio and hyper. Axum is a sensible default; Actix Web and Rocket are mature alternatives, Leptos targets full-stack reactive apps and Loco adds a Rails-like layer.
A router from the Tokio team built on tower services, so middleware for timeouts, tracing and compression is shared across the ecosystem. Handlers are plain async functions whose arguments are extractors like Json<T> and State<S>.
Actix Web is a mature, high-performance framework with its own runtime layer on Tokio, extractors, middleware and WebSocket support.
A framework that leans on macros and types for routing (#[get("/")]), request guards and typed forms, with a focus on ergonomics.
A full-stack framework with fine-grained signals in the style of SolidJS. Components compile to WebAssembly in the browser and render on the server, and server functions call backend code directly.
A batteries-included framework inspired by Rails, built on Axum and SeaORM, with generators, background jobs, mailers and authentication.
Async Rust needs a runtime that schedules futures and drives non-blocking I/O. Runtimes are not interchangeable at the I/O layer, so a project usually commits to one, and Tokio is what most libraries assume.
The dominant runtime: a work-stealing multi-thread scheduler, async TCP/UDP, timers, spawn, select!, async channels and spawn_blocking for blocking work. Start with #[tokio::main] and its tutorial.
A runtime that mirrored the standard library's API in async form. It has been discontinued and its maintainers point users to smol, so expect it only in older code.
A small, modular runtime made of separate crates (async-executor, async-io, blocking). Good for lightweight tools and for learning how executors work.
Beyond std::net for blocking sockets, the async ecosystem provides HTTP clients and servers and modern transports such as QUIC. These crates sit underneath most Rust web frameworks and SDKs.
The usual HTTP client: async by default with an optional blocking module, JSON helpers, cookies, proxies and a choice of TLS backends. Reuse one Client because it pools connections.
A low-level, correct HTTP/1 and HTTP/2 implementation used by reqwest, Axum and tonic. Use it directly when you need full control over connections rather than a framework.
An async implementation of QUIC, the UDP-based transport under HTTP/3, offering multiplexed streams without head-of-line blocking and built-in TLS 1.3.
Converting Rust values to and from formats like JSON, TOML and binary encodings. Serde separates data structures from formats, so one #[derive(Serialize, Deserialize)] works with every format crate.
The standard framework: derive the traits, then use a format crate like serde_json or toml. Attributes such as rename_all, default, skip_serializing_if and tag control the mapping without hand-written code.
The json crate offers a dynamically typed JsonValue with macros for building objects, convenient for loose data but without Serde's typed structs; most projects use serde_json instead.
The toml crate parses and writes TOML, the format of Cargo.toml, and works with Serde to load config files into structs. Use toml_edit when you must preserve comments and formatting.
Rust database libraries range from full ORMs to thin drivers; all aim to catch query mistakes at compile time where they can. Pick based on whether you want async, compile-time checked SQL or a query builder.
A synchronous ORM and query builder whose schema.rs lets the compiler check every query against your tables. Includes a CLI for migrations; diesel-async adds async connections.
Async SQL for Postgres, MySQL and SQLite without an ORM. The query! macros check raw SQL against a live database (or cached metadata) at compile time, and it ships pooling and migrations.
An ergonomic wrapper over SQLite's C library. The bundled feature compiles SQLite in so you have no system dependency, ideal for CLIs and desktop apps.
Use vetted libraries and high-level APIs, never hand-rolled primitives. The main choices are ring, the pure-Rust RustCrypto crates, and TLS through rustls.
A small, hard-to-misuse crypto library (AEAD, HKDF, ECDH, signatures, digests) with much of its core in assembly and C inherited from BoringSSL.
The original rust-crypto crate is long unmaintained; its successor is the RustCrypto project, a family of pure-Rust crates like sha2, aes-gcm, argon2 and ed25519-dalek sharing common traits.
Bindings to libsodium's easy APIs such as secretbox and box_. The project is deprecated, so new code should choose maintained RustCrypto crates or other libsodium bindings.
Rust is a great fit for command-line tools: one static binary, fast startup and solid cross-platform support. Parse arguments with clap, and add terminal crates for colours, prompts and full-screen interfaces.
The standard argument parser. With the derive feature a struct annotated #[derive(Parser)] becomes the CLI, giving subcommands, validation, env-var fallback, help text and shell completions.
The derive-based wrapper over clap 2 that inspired clap's own derive API. It is in maintenance mode; migrate to clap with #[derive(Parser)].
A pure-Rust, Unix-only crate for raw mode, cursor movement, colours and key events. For cross-platform terminal UIs, crossterm with ratatui is the common pairing.
Rust's performance and safety suit games, from data-driven ECS engines to minimal frameworks for 2D games. The ecosystem is young, so expect APIs that still change between releases.
A data-driven engine built around an entity component system: systems are plain functions querying components, scheduled in parallel automatically. Popular and fast-moving, with breaking changes each release.
A full 2D and 3D engine with a scene editor, closer to a traditional Unity or Godot workflow than Bevy's code-first approach.
A lightweight 2D framework inspired by LÖVE: a game loop with update and draw, sprites, sound and input, without an engine's structure.
A simple immediate-mode 2D library with very few dependencies that builds for desktop, web and mobile from the same code; good for jams and prototypes.
A safe graphics API implementing the WebGPU standard over Vulkan, Metal, DirectX 12 and WebGL. Engines like Bevy render with it; use it directly for custom renderers and GPU compute.
Desktop GUI in Rust is still settling. Options range from web front ends in a native shell, to native toolkit bindings, to pure-Rust retained-mode and GPU-rendered libraries.
Builds desktop and mobile apps with any web front end and a Rust backend, using the system webview instead of bundling Chromium, so installers are small. Commands expose Rust functions to JavaScript.
Safe bindings to GTK 4 and the GLib object system, the natural choice for Linux desktop apps that should look native on GNOME.
A cross-platform, pure-Rust GUI library based on the Elm architecture: state, messages, update and view. Renders with wgpu, with a software fallback.
The GPU-accelerated UI framework built by the Zed editor team, combining retained and immediate-mode styles. Powerful but young, with documentation still catching up.
Rust runs on microcontrollers with #![no_std], using core and optionally alloc instead of the full standard library. Peripheral access crates, hardware abstraction layers and portable driver traits form a layered ecosystem.
Traits for GPIO, SPI, I2C, delays and more. Drivers written against them run on any chip whose HAL implements the traits, so one sensor driver serves many boards.
Access to GPIO, I2C, PWM, SPI and UART on the Raspberry Pi from Linux user space, with optional embedded-hal trait implementations.
Hardware abstraction layers for Nordic nRF51, nRF52 and nRF91 microcontrollers, implementing embedded-hal for their peripherals.
Rust compiles to WebAssembly with no runtime or garbage collector, which keeps modules small. Targets include wasm32-unknown-unknown for the browser and WASI targets for server-side runtimes.
Generates the glue that passes strings, objects and closures between Rust and JavaScript. Mark exports with #[wasm_bindgen]; web-sys and js-sys expose browser APIs.
Builds a crate to Wasm, runs wasm-bindgen and packages the result as an npm module for bundlers, Node.js or plain web pages.
A runtime for running Wasm modules outside the browser, with WASI support and an embedding API so a Rust host can safely execute plugins.
Debug builds include symbols by default. Rust ships wrapper scripts that load pretty-printers into GDB and LLDB, and editors such as VS Code with CodeLLDB give graphical breakpoints. dbg! and RUST_BACKTRACE=1 cover a lot before you need a debugger.
A wrapper installed with the toolchain that starts GDB with Rust pretty-printers, so Vec, String and Option display readably. Typical on Linux.
The same idea for LLDB, the default debugger on macOS. Set breakpoints with b file.rs:42, step with n and s, and inspect values with p or frame variable.
Doc comments (/// for items, //! for modules and crates) are Markdown that cargo doc turns into HTML, and docs.rs builds automatically for published crates. Code blocks inside them run as tests, so examples stay correct, and intra-doc links like [Vec] resolve to the right page.
Measure in --release, then profile with perf, cargo flamegraph or Instruments to find hot spots. Common wins are fewer allocations and clones, better data layout, and build settings such as LTO and codegen-units = 1.
A statistics-driven benchmarking library that runs on stable Rust. It warms up, samples many iterations, reports confidence intervals and flags regressions against the previous run; use black_box so work is not optimised away.