Bitpath

Rust

Learn Rust from ownership up: moves, borrowing, enums, traits, lifetimes and threads, with the compiler as your teacher. Every snippet really compiles, and many exercises are about the lines it refuses.

  • Intermediate
  • 4 units, 12 lessons, 156 exercises
  • Rust
  • Builds on one other language; How Computers Work helps

Unit 01 · 3 lessons

Ownership

Predict when a value moves, when it is dropped and which borrows the compiler allows

  1. > start01Values
  2. 02Ownership and moves
  3. BOSSBorrowing
Unit prize
  1. 01
    Values

    Bindings, shadowing and code that is all expressions

  2. 02
    Ownership and moves

    One owner per value, and assignment hands it over

  3. BOSS
    Borrowing

    Lend a value instead of giving it away

Read the unit guide

Rust has no garbage collector and no manual free. Instead every value has exactly one owner, a variable, and the value is dropped at the line where its owner goes out of scope. The compiler works this out before the program runs.

Bindings are immutable unless declared let mut. A second let with the same name shadows the first with a brand new variable, which may even have another type. Blocks, if and loop are expressions: their value is the last line without a semicolon.

Assigning a String or a Vec to another variable, or passing it to a function, moves it: the old name is dead and using it is a compile error. Small fixed-size values (integers, floats, bool, char) are Copy and are duplicated instead. clone makes a real second copy when you want one.

Most code borrows instead of moving. &x lends a value for reading and &mut x lends it for writing. The rule is many readers or one writer, never both at once, and no reference may outlive the value it points to. A borrow lasts until the reference is last used.

String owns its text on the heap. &str is a borrowed view into text owned by someone else: a pointer and a length. Take &str in parameters and slice with &s[a..b].

The classic pitfall is fighting the borrow checker by cloning everything. Read the error instead: it names the line of the borrow, the line of the conflict and the line where the borrow is still used.

Unit 02 · 3 lessons

Types that carry meaning

Model data with structs and enums so that the wrong program fails to compile

  1. 01Structs and enums
  2. 02Pattern matching
  3. BOSSErrors as values
Unit prize
  1. 01
    Structs and enums

    Fields, methods and variants that hold data

  2. 02
    Pattern matching

    Cover every case, and take values apart by shape

  3. BOSS
    Errors as values

    Result, the ? operator and honest unwraps

Read the unit guide

A struct groups named fields, like a Python dataclass with fixed types. Its methods live in a separate impl block. The first parameter says what the method does with the value: &self reads it, &mut self changes it and self consumes it.

An enum is a type that is exactly one of several variants, and each variant can carry its own data. A shape that is a circle or a rectangle, a message that is a key press or a click: an enum makes the impossible combinations unrepresentable.

match takes a value apart by its shape. It must cover every case, so adding a variant makes the compiler point at every match that forgot it. Patterns also destructure structs and tuples, and _ catches everything else.

There is no null. A value that may be missing is an Option<T>: Some(value) or None, and you cannot use it as a T until you have checked. if let handles one case, let ... else handles the other one first and carries on.

Errors are values too. A function that can fail returns Result<T, E>: Ok(value) or Err(error). The ? operator passes an error up to the caller in one character, and map_err turns one error type into another.

The pitfall is unwrap. It compiles, and it crashes the program when the value is not there. Use it (or expect with a message) only where a failure would be a bug in your own code, never for input you do not control.

Unit 03 · 3 lessons

Abstraction

Share behaviour with traits and generics, and read the lifetimes that tie references together

  1. 01Traits
  2. 02Generics
  3. BOSSLifetimes
Unit prize
  1. 01
    Traits

    Named sets of methods that any type can implement

  2. 02
    Generics

    One definition for many types, static or dynamic

  3. BOSS
    Lifetimes

    Tell the compiler which borrow a result comes from

Read the unit guide

Rust has no classes and no inheritance. Shared behaviour is a trait: a named set of methods. Any type can implement a trait with an impl Trait for Type block, and a trait can supply default methods built on the required ones.

The compiler writes the mechanical traits for you: #[derive(Debug, Clone, PartialEq)] above a type gives it {:?} printing, .clone() and ==. Display, the {} format meant for users, you write yourself.

A generic function fn f<T>(x: T) works for every type, so its body may only do what every type can do. A trait bound, T: PartialOrd, narrows the types and unlocks the trait's methods. The compiler builds one specialised copy per concrete type: static dispatch, with no cost at run time.

When the type is only known at run time, such as a list of mixed shapes, use a trait object: Box<dyn Area>. Each method call is looked up through a table: dynamic dispatch, the way every Python method call works.

Every reference has a lifetime, the stretch of code where it must stay valid. Inside a function the compiler works lifetimes out by itself. In a signature that returns a reference it needs to know which input the result borrows from. Three elision rules cover most cases, and otherwise you name it: fn longest<'a>(a: &'a str, b: &'a str) -> &'a str.

The pitfall is thinking an annotation keeps something alive. It never does. 'a is a claim about code that already exists, and the compiler checks the claim against every caller.

Unit 04 · 3 lessons

Real programs

Use iterators, smart pointers and threads, and know which ownership tool each one is

  1. 01Collections and iterators
  2. 02Smart pointers
  3. BOSSFearless concurrency
Unit prize
  1. 01
    Collections and iterators

    Loops that own or borrow, closures and lazy pipelines

  2. 02
    Smart pointers

    Box, Rc and RefCell, and what each one relaxes

  3. BOSS
    Fearless concurrency

    Threads that the borrow checker keeps honest

Read the unit guide

A for loop takes ownership choices like everything else. for x in v consumes the vector, for x in &v borrows each item and for x in &mut v lets you change items in place. While a loop borrows a collection, the collection cannot be changed.

Iterators are lazy. v.iter() does nothing by itself, and adapters such as map and filter only describe work. A consumer such as collect, sum or a for loop pulls the items through. Closures, written |x| x + 1, are inline functions that can use the variables around them. A HashMap has no fixed order when you iterate it.

Smart pointers are owners with extra rules. Box<T> puts a value on the heap behind a pointer of known size, which recursive types such as trees need. Rc<T> counts owners so that several can share one read-only value. RefCell<T> checks the borrow rules at run time instead of compile time, and panics when they are broken.

Threads follow the same ownership rules, and that is what makes them safe. A spawned thread must own what it uses, so its closure is marked move. Two threads cannot both hold &mut to one value, so a data race is a compile error.

To share data between threads use Arc<T>, the thread-safe Rc, and to change it wrap it in a Mutex<T>, which hands out one guard at a time. Channels move values from one thread to another. The marker traits Send and Sync are how the compiler knows which types may cross threads.

The pitfall is reaching for Rc<RefCell<T>> everywhere to get Python-style sharing back. It works, but every check it moves to run time is a panic waiting to happen. Plain ownership and borrowing come first.

Learn Rust on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy