Learn Rust

Fast, memory-safe systems language with no garbage collector

42 lessons · 10 hours · 4 levels · covers Rust 2024 edition (1.8x)

Rust is a compiled systems programming language that guarantees memory and thread safety at compile time through ownership and borrowing, without a garbage collector. It is used for command-line tools, web services, embedded firmware, WebAssembly, and performance-critical parts of browsers, operating systems and cloud infrastructure. Learning it teaches you to reason precisely about ownership, lifetimes and concurrency.

How deep do you want to go?

1. EssentialsRead and write simple code, do the everyday basics12 lessons · 2 hours in total
2. PracticalUse it productively at work, with the usual idioms25 lessons · 5 hours in total
3. AdvancedThe less common features, performance and trade-offs35 lessons · 8 hours in total
4. ExpertInternals and the edge cases experts know42 lessons · 10 hours in total

The Rust tree

RustCargo and your first programCargo and your firstprogramVariables and mutabilityVariables andmutabilityScalar and compound typesScalar and compoundtypesFunctions and expressionsFunctions andexpressionsControl flow: if, loop, while, forControl flow: if, loop,while, forOwnership and movesOwnership andmovesReferences and borrowingReferences andborrowingSlices and string slicesSlices and stringslicesStructs and methodsStructs and methodsEnums and matchEnums and matchOption, if let and let-elseOption, if let andlet-elsePatterns and destructuringPatterns anddestructuringResult and the ? operatorResult and the ?operatorVectorsVectorsString and UTF-8 textString and UTF-8 textHashMap and the entry APIHashMap and theentry APIModules, crates and packagesModules, crates andpackagesTraitsTraitsGenerics and trait boundsGenerics and traitboundsDerive and the standard traitsDerive and thestandard traitsClosuresClosuresIteratorsIteratorsLifetime annotationsLifetime annotationsTestingTestingBox, Rc and RefCellBox, Rc and RefCell
Essentials and Practical shown (25 of 42 lessons); the full list is below. Click a lesson to read it.

All 42 lessons, in order

Getting started

  1. Cargo and your first program · Essentials · 10 min

    Install Rust with rustup, create a project with cargo new, and build and run it with cargo run.

  2. Variables and mutability · Essentials · 8 min

    Bind values with let, opt into mutation with mut, and use shadowing and const where they fit.

  3. Scalar and compound types · Essentials · 12 min

    Integers, floats, bool and char, plus tuples and fixed-size arrays, and how Rust handles overflow and conversions.

  4. Functions and expressions · Essentials · 8 min

    Declare functions with typed parameters and return values, and understand why almost everything in Rust is an expression.

  5. Control flow: if, loop, while, for · Essentials · 10 min

    Branch with if, repeat with loop, while and for over ranges, and use labels and break values.

Ownership and borrowing

  1. Ownership and moves · Essentials · 15 min

    Every value has one owner; assignment moves ownership, and the value is freed when its owner goes out of scope.

  2. References and borrowing · Essentials · 15 min

    Lend access with & and &mut references, and learn the rule: many readers or one writer, never both.

  3. Slices and string slices · Essentials · 10 min

    Borrow part of an array, Vec or String as a slice (&[T] or &str) and write functions that accept any of them.

Structs, enums and patterns

  1. Structs and methods · Essentials · 12 min

    Group named fields into a struct, attach methods and associated functions in impl blocks, and pick the right self.

  2. Enums and match · Essentials · 12 min

    Model values that can be one of several variants, each with its own data, and handle every case with match.

  3. Option, if let and let-else · Essentials · 10 min

    Represent a value that may be absent with Option<T>, and unpack it with match, if let, let-else and combinators.

  4. Patterns and destructuring · Essentials · 10 min

    Use patterns everywhere: destructure structs and tuples, add guards, match ranges, and bind with @.

Errors and collections

  1. Result and the ? operator · Practical · 12 min

    Return Result<T, E> from fallible functions and propagate errors with ?, keeping panics for bugs.

  2. Vectors · Practical · 10 min

    Store a growable list in Vec<T>: create, push, index safely, iterate, and understand capacity.

  3. String and UTF-8 text · Practical · 12 min

    Work with owned String and borrowed &str, build and format text, and handle UTF-8 correctly.

  4. HashMap and the entry API · Practical · 10 min

    Store key-value pairs in HashMap, update counts and groups with the entry API, and know when to use BTreeMap or HashSet.

  5. Custom errors, thiserror and anyhow · Advanced · 15 min

    Design error types with std::error::Error, derive them with thiserror in libraries, and add context with anyhow in applications.

Modules, crates and testing

  1. Modules, crates and packages · Practical · 14 min

    Organise code into modules and files, control visibility with pub, and add dependencies in Cargo.toml.

  2. Testing · Practical · 12 min

    Write unit tests with #[test] and assert macros, integration tests in tests/, doc tests, and run them with cargo test.

Traits, generics and closures

  1. Traits · Practical · 14 min

    Define shared behaviour with traits, implement them for your types, and use default methods and impl Trait parameters.

  2. Generics and trait bounds · Practical · 14 min

    Write functions and types over any T, constrain T with trait bounds and where clauses, and know what monomorphization costs.

  3. Derive and the standard traits · Practical · 12 min

    Know Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, Default, Display and From/Into, and when to derive or implement them.

  4. Closures · Practical · 12 min

    Write anonymous functions that capture their environment, understand Fn, FnMut and FnOnce, and use move closures.

  5. Iterators · Practical · 15 min

    Chain lazy iterator adapters like map, filter and enumerate, finish with collect, sum or fold, and implement Iterator.

  6. Trait objects and dyn · Advanced · 14 min

    Use dyn Trait for runtime polymorphism, understand vtables and fat pointers, and know the dyn-compatibility rules.

Smart pointers and lifetimes

  1. Lifetime annotations · Practical · 15 min

    Read and write lifetime parameters like 'a that tell the compiler how returned references relate to inputs.

  2. Box, Rc and RefCell · Practical · 15 min

    Put values on the heap with Box, share ownership with Rc, and mutate shared data with RefCell.

  3. Lifetimes in depth · Advanced · 18 min

    Outlives bounds, what T: 'static really means, higher-ranked bounds, and how impl Trait captures lifetimes in Rust 2024.

  4. Interior mutability: Cell, OnceCell, LazyLock · Advanced · 14 min

    Mutate through shared references safely with Cell, RefCell, OnceCell and LazyLock, and see how UnsafeCell underpins them all.

Concurrency and async

  1. Threads and scoped threads · Advanced · 14 min

    Spawn OS threads, move data into them, join their results, and borrow local data safely with thread::scope.

  2. Arc, Mutex and RwLock · Advanced · 15 min

    Share data across threads with Arc, guard mutation with Mutex or RwLock, use atomics for counters, and avoid deadlocks.

  3. Message passing with channels · Advanced · 12 min

    Send values between threads with mpsc channels, use bounded channels for backpressure, and shut down cleanly.

  4. async/await and futures · Advanced · 18 min

    Understand what async fn returns, why futures are lazy, how executors poll them, and when async beats threads.

  5. Tokio basics · Advanced · 18 min

    Run async code on the Tokio runtime: #[tokio::main], spawn, join!, select!, timeouts, async channels and spawn_blocking.

  6. Send and Sync · Expert · 15 min

    The auto traits that make data races impossible: what Send and Sync mean, which std types lack them, and when to implement them unsafely.

  7. Pin and self-referential futures · Expert · 20 min

    Why async state machines can't move, what Pin and Unpin guarantee, how to pin with Box::pin and pin!, and how pin projection works.

Macros, unsafe and internals

  1. Declarative macros (macro_rules!) · Advanced · 16 min

    Write macro_rules! macros with fragment specifiers and repetitions, understand hygiene, and export them from a crate.

  2. Unsafe Rust and raw pointers · Expert · 20 min

    What unsafe unlocks, raw pointers and &raw, writing sound safe abstractions, SAFETY comments, the 2024 edition rules and Miri.

  3. Memory layout, repr and niches · Expert · 16 min

    How Rust lays out structs and enums: size and alignment, field reordering, repr(C), repr(transparent), niche optimisation and DSTs.

  4. Variance and PhantomData · Expert · 18 min

    How lifetimes subtype, why &mut T is invariant, and how PhantomData declares ownership, variance and auto traits for unused type parameters.

  5. Procedural macros · Expert · 20 min

    Write derive, attribute and function-like procedural macros with proc_macro, syn and quote, with good error spans.

  6. FFI: calling C and being called from C · Expert · 20 min

    Declare foreign functions in unsafe extern blocks, export extern "C" functions, pass strings, structs and callbacks, and keep ownership straight.