Rust Tutorial
Learn Rust 1.99 from your first program to ownership, traits, iterators, concurrency, async and real projects. 132 lessons with Rust that compiles and runs in your browser, quizzes and projects.
Start learning →
of lessons completed
Getting Started
- Getting Started with Rust Learn what Rust is, why it is fast and memory safe without a garbage collector, who uses it, what editions are, and run your first Rust program right in the browser.
- How Rust Works: rustc, Cargo and the Toolchain See what happens between your Rust source and a running program: rustc, MIR, LLVM, Cargo, rustup, crates.io, debug versus release builds, editions and what the compiler checks.
- Rust Syntax Learn the shape of Rust code - items, statements and expressions, the missing-semicolon rule, blocks, naming conventions, attributes and how to read compiler error codes.
- Cargo, Projects and Crates Learn Cargo, Rust's build tool - cargo new, build, run, check and test, the Cargo.toml file, src layout, dependencies and semver, features, workspaces, Cargo.lock, rustfmt and clippy.
- Comments and Documentation Learn Rust comments - line and block comments, /// and //! doc comments with Markdown, doc tests, rustdoc, and how #[allow], #[warn] and #[deny] control compiler lints.
- Printing with println! and format! Master Rust output - println!, print!, eprintln!, format!, write! and dbg!, placeholders, width, precision, alignment, fill, hex, binary and scientific formats, and Display versus Debug.
- Reading Input Learn how to read user input in Rust with std::io::stdin, read_line, lines and read_to_string, why the newline stays, how parse works and how to handle bad input safely.
- The main Function, Arguments and Exit Codes Learn how Rust programs start and end - fn main, returning Result or ExitCode, process::exit, env::args, exit status 101 for panics and how Termination works.
- Rust Compared with C++, Go and Python Compare Rust with C++, Go and Python on memory safety, concurrency, performance, errors and ecosystem, and learn when Rust is the right tool and when another language wins.
- Rust Learning Roadmap and Popular Crates A practical Rust learning path from basics to async and unsafe, plus a tour of the crates you will meet (serde, tokio, clap, rand, anyhow, rayon, reqwest) and notes on Rust careers.
Variables and Types
- Variables and Mutability Learn Rust variables - let, immutability by default, mut, shadowing versus mutation, type inference, late initialization, const, static and why unused variable warnings matter.
- Integers, Floats, bool and char A complete guide to Rust's scalar types - i8 to i128, u8 to u128, isize and usize, number literals, f32 and f64, bool and char as a 4-byte Unicode scalar value, MIN, MAX and size_of.
- Integer Overflow and Arithmetic Understand Rust integer overflow - panics in debug builds, wrapping in release, checked_, wrapping_, saturating_ and overflowing_ methods, Wrapping, division, rem_euclid, abs_diff and NaN.
- Type Conversion and Casting Learn how to convert between types in Rust - as casts, truncation and saturation, From and Into, TryFrom and TryInto, parse, usize indexing and char, u8 and u32 conversions.
- Tuples and the Unit Type Learn Rust tuples - creating them, indexing with .0, destructuring, nesting, returning several values, comparing and printing tuples, and the unit type () that functions return by default.
- Arrays Learn Rust arrays - the [T; N] type, array literals and repeat syntax, bounds-checked indexing, iteration, 2D arrays, useful methods, and how arrays differ from slices and Vec.
- String and &str Basics Learn the two Rust string types, String and &str - literals, creating and growing strings, + and format!, UTF-8 and len() in bytes, and why a string cannot be indexed by integer.
- Type Aliases, the Never Type and Inference Learn Rust type aliases, the never type ! in panic, loop and return, how type inference works, the turbofish ::<>, Default::default() and the basics of size_of and alignment.
Operators and Control Flow
- Operators Learn all Rust operators - arithmetic, comparison, short-circuit logic, bitwise and shifts, compound assignment, why there is no ++, precedence, ranges and how operators map to traits.
- if, else if and else Learn Rust if expressions - conditions must be bool, getting values out of branches, else if chains, if let, let chains in the 2024 edition, early return and why Rust has no ternary operator.
- match Expressions Learn Rust match from scratch - arms, exhaustive checking, ranges, guards, @ bindings, tuples, enums with data, match as an expression and the compiler errors you will meet.
- loop, while and for Learn Rust loops - loop with break values, while, while let, for over ranges and iterators, continue, labeled breaks, step_by, rev and why for beats index loops.
- Patterns in Depth Master Rust patterns - destructuring structs, enums, tuples and slices, refutable vs irrefutable patterns, ref and ref mut, @ bindings, let-else and the matches! macro.
- Option and Handling Absence Learn Rust's Option type - why Rust has no null, Some and None, match and if let, unwrap and expect, unwrap_or, map, and_then, filter, ok_or and the ? operator.
Ownership and Borrowing
- Ownership Understand Rust ownership from the ground up - stack and heap, the three ownership rules, moves, Copy versus Clone, drop at scope end and ownership in function calls.
- References and Borrowing Learn Rust references and borrowing - &T and &mut T, the one-writer-or-many-readers rule, dereferencing, dangling references and the errors E0382, E0499, E0502 and E0505.
- The Borrow Checker in Practice Learn how the Rust borrow checker works: non-lexical lifetimes, two-phase borrows, reborrowing, split borrows, and a toolbox of fixes for E0499, E0502, E0506.
- Slices Learn Rust slices: &[T] and &str, ranges, split_at, chunks, windows, binary_search, sort, slice patterns and the UTF-8 character boundary panic.
- Copy, Clone and Move Semantics Understand Rust Copy and Clone, when assignment moves or copies, what cloning costs, and how mem::swap, replace and take move values out of borrowed places.
- Lifetimes Understand Rust lifetimes: the 'a syntax, elision rules, structs holding references, multiple lifetimes, 'static, and the errors E0106 and E0597.
- Lifetime Patterns and Pitfalls Practical Rust lifetime patterns: returning references, why self-referential structs fail, T: 'a bounds, the '_ lifetime and owning vs borrowing.
- Box and the Heap Learn Rust Box<T> for heap allocation: recursive types like linked lists and expression trees, trait objects, Deref, deref coercion and drop order.
Structs, Enums and Traits Basics
- Structs Learn Rust structs - named-field, tuple and unit structs, field init shorthand, struct update syntax, ownership of fields, derive Debug, memory layout and builders.
- Methods and Associated Functions Learn Rust methods and associated functions - impl blocks, &self, &mut self and self, new constructors, method chaining, associated constants and the Self type.
- Enums Learn Rust enums - variants that carry data, Option and Result as enums, impl on enums, C-like enums with discriminants, enum size and state machines.
- Modelling with Enums and Pattern Matching Design with Rust enums and match - expression trees, command parsers, state machines, replacing class hierarchies, exhaustive matches as a refactoring net, non_exhaustive.
- Traits Learn Rust traits - define and implement them, default methods, trait bounds, the orphan rule, derive macros (Debug, Clone, PartialEq, Hash, Ord, Default) and a tour of standard traits.
- Trait Objects and Dynamic Dispatch Learn Rust trait objects - dyn Trait, Box<dyn Trait>, vtables, object safety, static vs dynamic dispatch, heterogeneous collections and downcasting with Any.
- Display, From and Standard Conversion Traits Learn Rust conversion traits: Display and ToString, From and Into, TryFrom, FromStr, AsRef, Default and hand-written PartialEq and PartialOrd.
- Operator Overloading Overload operators in Rust with std::ops: Add, Sub, Mul, Neg, AddAssign and Index, plus PartialEq, Ord, and implementations for references.
Generics
- Generics Learn Rust generics: generic functions, structs, enums and impl blocks, monomorphization, the turbofish, default parameters and generics vs trait objects.
- Trait Bounds and where Clauses Learn Rust trait bounds: multiple bounds with +, where clauses, impl Trait in arguments and return types, blanket impls and conditional methods.
- Associated Types and Generic Traits Understand Rust associated types vs generic trait parameters: Iterator::Item, default parameters like Add<Rhs=Self>, and stable GATs.
- Const Generics Learn Rust const generics: code over any [T; N], a Matrix<R, C> with compile-time shape checks, const fn, braces, defaults and stable limits.
- Advanced Traits: Supertraits, Newtype and Disambiguation Go beyond basic traits in Rust - supertraits, fully qualified syntax, the newtype pattern and orphan rule, marker traits, PhantomData, trait upcasting and impl Trait versus dyn.
- Type-State and Builder Patterns Design Rust APIs that cannot be misused - the type-state pattern with PhantomData, owned and borrowed builders, compile-time required fields, sealed traits and generic API guidelines.
Collections and Iterators
- Vec Learn Rust's Vec from scratch - creating vectors, push and pop, indexing versus get, capacity, sorting, dedup, retain, drain, extend, nested vectors, vectors of enums and performance.
- String Handling in Depth Master Rust strings - String versus &str, UTF-8 and byte indexes, chars and bytes, split and trim, find and replace, parse, format!, case conversion, capacity and common Unicode pitfalls.
- HashMap and HashSet Learn Rust's HashMap and HashSet - insert, get and the entry API, ownership of keys and values, random iteration order, BTreeMap for sorted keys, set operations and custom Hash and Eq.
- VecDeque, BinaryHeap and Other Collections Learn Rust's other collections - VecDeque ring buffer, BinaryHeap priority queue with Reverse, why LinkedList is rare, BTreeMap range queries and a table for choosing the right collection.
- Iterators Learn Rust iterators from scratch - the Iterator trait, next(), iter, iter_mut and into_iter, lazy adapters like map and filter, consumers like sum and collect, and common pitfalls.
- Iterator Patterns and Collecting Master Rust iterator recipes - collect into Vec, HashMap, String and Result, flat_map, scan, take_while, partition, unzip, chunk_by, fold-based grouping and hand-written itertools helpers.
- Writing Your Own Iterators Learn to implement Rust's Iterator trait, IntoIterator for your collections and references, DoubleEndedIterator, ExactSizeIterator, impl Iterator returns, from_fn and successors.
- Closures Understand Rust closures - syntax, capturing by borrow, mutable borrow or move, the Fn, FnMut and FnOnce traits, passing and returning closures, boxing them, and async closures.
- Sorting, Searching and Comparison Learn to sort and search in Rust - sort, sort_by, sort_by_key, sort_unstable, Ordering, Reverse, sorting floats with total_cmp, binary_search, derive Ord and stable versus unstable sorts.
- The HashMap Entry API in Depth Master the Rust HashMap entry API: or_insert, or_insert_with, or_default, and_modify, matching on Entry, plus counting, grouping and nested map patterns.
Error Handling
- Panics Learn how Rust panics work - panic!, unwrap and expect, index out of bounds, integer overflow, unwinding versus abort, RUST_BACKTRACE, catch_unwind and when a panic is the right choice.
- Result and Recoverable Errors Learn how Rust handles failure with Result<T, E>: matching Ok and Err, unwrap_or, map, map_err, and_then, ok_or, early returns and a strategy.
- The ? Operator Learn the Rust ? operator: propagating errors, automatic From conversion, using ? with Option, main returning Result, chaining calls and common errors.
- Custom Error Types Build your own Rust error types: error enums, Display and std::error::Error, source() chains, From for ?, Box<dyn Error>, plus thiserror and anyhow explained.
- Error Handling Design Design good Rust error handling: libraries vs applications, typed errors instead of strings, adding context, retrying, collecting validation errors, logging.
Modules, Packages and Macros
- Modules Learn Rust modules: mod blocks, pub and private items, pub(crate) and pub(super), use, as, glob and nested imports, crate/self/super paths and re-exports.
- Crates, Dependencies and Features Understand Rust crates: library vs binary crates, Cargo.toml dependencies, semver, features, workspaces, build.rs, publishing to crates.io and key ecosystem crates.
- Declarative Macros (macro_rules!) Learn Rust declarative macros with macro_rules!: fragments, repetitions, recursion, hygiene, and how to build vec!-like and hashmap! macros step by step.
- Procedural and Derive Macros Understand Rust procedural macros: derive, attribute and function-like macros, what #[derive(Debug)] expands to, how serde works, and a proc-macro crate sketch.
- Attributes, cfg and Conditional Compilation Learn Rust attributes: derive, cfg and cfg!, #[cfg(test)], inline, must_use, repr, allow, deprecated, cfg_attr, feature flags and target_os checks with examples.
Smart Pointers and Memory
- Rc, Arc and Shared Ownership Learn Rust Rc<T> and Arc<T> for shared ownership: strong_count, clone cost, Rc<RefCell<T>>, Weak pointers, parent links in trees, reference cycles and threads.
- Interior Mutability: Cell and RefCell Learn Rust interior mutability with Cell, RefCell, OnceCell and LazyCell: runtime borrow checking, BorrowMutError panics, Rc<RefCell<T>> graphs and when to avoid them.
- Drop and RAII Master Rust's Drop trait and RAII: when drop runs, drop order for locals, fields and temporaries, mem::drop, mem::forget, scope guards, locks, files and panics.
- Memory Layout and Sizes See how Rust lays values out in memory: size_of and align_of, padding, field reordering, repr(C), niche optimization, stack versus heap, and zero-sized types.
- Cow, Borrow and Avoiding Clones Learn when Rust code really needs to allocate. Cow<str>, ToOwned, Borrow, AsRef, choosing &str over String in APIs, and zero-copy parsing with slices.
- Unsafe Rust Learn what unsafe Rust really allows, how raw pointers work, how to build safe abstractions like split_at_mut, why static mut is dangerous, and how Miri finds bugs.
- FFI: Calling C and Being Called Call C functions from Rust and expose Rust functions to C. Learn unsafe extern blocks, repr(C), CString and CStr, callbacks, no_mangle in 2024, bindgen and cbindgen.
- Python Extensions with PyO3 Learn how PyO3 and maturin let you write fast Python extension modules in Rust, with #[pyfunction], #[pyclass], type conversion, error mapping, the GIL and release builds. Read-only, with runnable stand-ins.
Concurrency
- Threads Learn Rust threads: thread::spawn and JoinHandle, move closures, returning values, panics in threads, scoped threads, Builder names, and the Send and Sync traits.
- Message Passing with Channels Send data between Rust threads with std::sync::mpsc channels: send and recv, multiple producers, closing, try_recv, bounded sync_channel, and worker patterns.
- Shared State: Mutex and RwLock Learn shared-state concurrency in Rust: Arc<Mutex<T>>, lock guards, poisoning, try_lock and deadlocks, RwLock, Condvar, Barrier and how to avoid lock contention.
- Atomics and Memory Ordering Learn Rust atomics: AtomicUsize and AtomicBool, fetch_add, compare_exchange, Relaxed, Acquire, Release and SeqCst ordering, a spin lock, Once, OnceLock and LazyLock.
- Send, Sync and Fearless Concurrency Understand Rust's Send and Sync marker traits: why Rc is not Send, why RefCell is not Sync, how the compiler rejects data races, and how to design thread-safe types.
- Parallel Patterns Without Libraries Split work across threads using only std: thread::scope with chunks, parallel sum and map, chunks_mut, a work queue, a hand-built thread pool, and how Rayon does it.
- thread_local!, OnceLock and LazyLock Learn safe global state in Rust: thread_local! with Cell and RefCell, OnceLock for set-once config, LazyLock for lazy statics, LazyCell, and why static mut is a trap.
Async Rust
- Async/await Basics Learn how Rust async/await works: futures are lazy state machines, async fn and async blocks, .await, why std has no runtime, a tiny block_on, Pin at a glance, and async vs threads.
- Futures and Executors by Hand Implement Rust's Future trait yourself: Poll, Pin and Context, a Wake-based block_on executor that parks the thread, a thread-backed timer future, and a join of two futures.
- Async Patterns with a Mini Runtime Learn async Rust patterns by building them: a task executor with spawn and JoinHandle, channels between tasks, select, cancellation by drop, poll_fn, and async closures.
- Tokio and the Async Ecosystem Tour Tokio and the async Rust ecosystem: tokio::main, spawn, JoinSet, select!, channels, async I/O, why futures must be Send, blocking pitfalls, and runtime choices.
Standard Library Tour
- Time, Duration and Instant Work with time in Rust: Duration arithmetic, measuring with Instant, SystemTime and UNIX_EPOCH, formatting durations and dates by hand, sleeping, and testable clocks.
- Files and the Filesystem Read and write files in Rust with std::fs, File, BufReader and BufWriter, Path and PathBuf, OpenOptions, io::Error kinds, and a recursive directory walk, all runnable.
- Read, Write and BufRead Traits Master Rust's I/O traits: write code generic over Read, Write and BufRead, use Cursor and Vec<u8>, lock stdout, implement your own Write adapter, and parse bytes.
- Environment, Processes and Signals Use environment variables, command-line arguments, exit codes and child processes in Rust, understand why env::set_var is unsafe in 2024, and handle Unix signals.
- Networking with std::net Learn Rust networking with std::net: parse IP and socket addresses, build a TCP echo server and client on loopback with threads, send UDP datagrams and set timeouts.
- JSON, Serialization and Text Formats by Hand Build a JSON value type, printer and parser in plain Rust, write a CSV reader with quoting, learn escaping rules, and see how serde derives Serialize and Deserialize.
- Randomness, Hashing and Math Write seeded random generators (LCG, xorshift, PCG) by hand, shuffle fairly, use Hash and Hasher with a custom FNV hasher, and master f64 math, isqrt and gcd in Rust.
- Parsing Text: Hand-Written Parsers Learn to parse text in Rust by hand: tokenizers with Peekable<Chars>, recursive-descent expression evaluators, FromStr, parser combinators, and when to use regex or nom.
- Bit Manipulation and Integer Tricks Learn bit manipulation in Rust: shifts, masks, set and clear bits, count_ones, leading_zeros, rotate, bit packing and building bitflags by hand.
- Serialization and Data Formats by Hand Build a serde-style Serialize trait and Serializer formats in plain Rust, write JSON and a binary format from the same code, and see how derive and TOML fit in.
Testing and Tooling
- Testing in Rust Learn Rust testing: #[test] functions, assert!, assert_eq!, should_panic, Result-returning tests, unit versus integration tests, cargo test output and a runnable test harness.
- Test Patterns: Fixtures, Doc Tests and Property Tests Learn practical Rust test patterns: doc tests, helper fixtures, table-driven tests, a hand-rolled property tester with shrinking, snapshot tests and mocking with traits.
- Debugging, Logging and Diagnostics Debug Rust with dbg!, Debug output, readable panics and backtraces, assert and debug_assert, a hand-made logger, rust-gdb, lldb and Miri.
- Clippy, rustfmt and Code Quality Keep Rust code clean with Clippy lints and before/after fixes, rustfmt, the Cargo lints table, allow and expect, cargo audit and a CI setup.
- Performance and Optimization Make Rust fast the right way: release builds, zero-cost iterators, counting allocations, with_capacity, avoiding clones, black_box and profiling.
- Release Builds, Cross-Compilation and Deployment Ship Rust programs: release profiles, Cargo features and cfg, cross-compiling targets, static musl binaries, Docker builds and WebAssembly.
- Testing Unsafe Code with Miri and Sanitizers Audit unsafe Rust: run tests under Miri, explore thread interleavings with loom, use AddressSanitizer and ThreadSanitizer, and add cheap debug assertions and leak counters.
- Property Testing and Fuzzing Test Rust with properties instead of examples: random inputs, shrinking, round-trip and invariant checks, plus fuzzing with cargo-fuzz. Build a mini property runner and fuzzer.
- Benchmarking Rust Code Measure Rust performance correctly: Instant timing, warm-up and calibration, black_box, medians and outliers, criterion and divan, and the pitfalls that fool benchmarks.
Advanced Rust
- Advanced Trait Techniques Go deeper with Rust traits: blanket impls, extension traits, generic trait objects, dyn compatibility, specialization status and impl Trait in traits.
- Pin, Unpin and Self-Referential Types Learn why Rust has Pin, Unpin and PhantomPinned: how moves break self-referential structs, Pin<Box<T>>, projection and async state machines.
- Type System Techniques Use Rust's type system to make bugs impossible - zero-sized types, unit newtypes, PhantomData, typestate, the never type, const evaluation and branded handles, with runnable code.
- Macros in Practice: DSLs Build real macro_rules! macros - a hand-written matches!, a struct builder generator, a tiny HTML DSL with a tt muncher - plus hygiene traps and when not to use macros.
- Building Data Structures with Unsafe Build a Vec clone on std::alloc and a raw-pointer queue in Rust, learn the invariants, Drop, PhantomData, SAFETY comments, leak counting and how Miri finds undefined behavior.
- Embedded, no_std and WebAssembly Learn what #![no_std] means, how core, alloc and std differ, how embedded HAL traits work and how Rust compiles to WebAssembly, with runnable stand-ins for code you cannot run online.
- What's New in Rust 2021 to 1.99 A guided tour of the Rust features added since the 2021 edition - let-else, GATs, async closures, LazyLock, trait upcasting, let chains and the 2024 edition changes - each with runnable code.
- MaybeUninit, transmute and Raw Memory Learn Rust's low-level memory tools: MaybeUninit for uninitialized data, transmute and its rules, ptr::read and write, ManuallyDrop, mem::zeroed and safer alternatives.
- Inline Assembly and SIMD Learn Rust's lowest-level performance tools: the asm! macro, core::arch intrinsics with runtime feature detection, portable std::simd, and how to help auto-vectorization.
- Design Patterns in Rust See how classic design patterns look in Rust: strategy with traits and closures, visitor, observer, command with undo and RAII guards, built on ownership.
- Web Services in Rust Learn how Rust web frameworks work: path routing, extractor traits, IntoResponse, shared state with Arc and Mutex, middleware, and a loopback server built by hand.
Projects
- Project: Guessing Game Build a number guessing game in Rust in stages - reading input, parsing, Ordering, loops, a seeded random generator without crates, custom errors and tests with no keyboard needed.
- Project: Command-Line To-Do Manager Build a to-do manager in Rust step by step: structs and enums for the model, a command parser with FromStr, text persistence, an input loop and tests.
- Project: A grep Clone Build a grep clone in Rust: a search function with lifetimes, case-insensitive matching, argument parsing, a tiny wildcard matcher, error types, exit codes and tests.
- Project: Bank Account System Build a bank in Rust in stages: a Money type, an Account trait with trait objects, typed errors, safe transfers past the borrow checker, then Rc/RefCell and Arc/Mutex variants.
- Project: A Tiny HTTP Server Build an HTTP/1.1 server from scratch in Rust: parse requests safely, write responses, route paths with parameters, run a thread pool and test it with a client in the same program.
- Project: An Expression Interpreter Build a calculator language in Rust: a tokenizer, a recursive-descent parser with operator precedence, an AST of enums, an evaluator and error messages that point at the exact column.
- Project: A Concurrent Job Pipeline Build a concurrent crawler in Rust with worker threads and channels: share a job queue, aggregate results, apply backpressure, retry failures, survive panics and shut down cleanly.
- Building CLI Tools: Arguments, Logging and Errors Build a command-line tool in Rust: parse subcommands and flags, add leveled logging, wrap errors with context and return proper exit codes, then map it to clap, tracing and anyhow.
- Project: Text Adventure Engine Build a text adventure in Rust: model rooms, items and commands as enums, parse input safely, share behavior with a trait and drive the game with a small state machine.
- Project: LRU Cache with Safe and Unsafe Variants Build an LRU cache three ways in Rust: a simple VecDeque version, an O(1) safe version with an index-linked list, and a raw-pointer version with unsafe and Drop.
Practice and Review
- Rust Cheat Sheet A one-page Rust cheat sheet for Rust 1.99: syntax, ownership rules, common traits, collections, iterator adapters, error handling and a compiler error index.
- Reading Compiler Errors Learn to read rustc errors and fix the common ones: E0382, E0499, E0502, E0505, E0308, E0277, E0599, E0106, E0425, E0597, E0004 and E0373, with real output.
- Practice Problems: Fundamentals 15 graded Rust practice problems with hints and verified solutions: loops, numbers, strings, ownership, structs, enums, Option and Result. Run Rust in your browser.
- Data Structures in Safe Rust Build a linked list with Option<Box>, a binary search tree, an index-based graph and a segment tree in safe Rust, then make them generic. Learn why ownership shapes each design.
- Practice Problems: Traits, Iterators and Concurrency 15 harder Rust practice problems with hints and verified solutions: traits, generics, operators, iterators, closures, errors, lifetimes, Rc, threads and channels.
- Rust Interview Questions and Answers 52 common Rust interview questions with concise answers and runnable code: ownership, lifetimes, traits, errors, iterators, Rc and Arc, Send and Sync, async, unsafe.