Bitpath

Rust: Zero to Hero

Programming from nothing, in Rust: values, decisions, loops, functions, ownership and collections, then your own types, errors, traits and threads. Every snippet really compiles, and the compiler is treated as a tutor whose messages you learn to read.

  • Beginner
  • 8 units, 24 lessons, 312 exercises
  • Rust
  • No experience needed; the steepest of the five

Unit 01 · 3 lessons

First steps

Read and write small programs that compute with numbers and text

  1. > start01Values and expressions
  2. 02Variables and types
  3. BOSSA receipt
Unit prize
  1. 01
    Values and expressions

    Printing, numbers, text and arithmetic

  2. 02
    Variables and types

    Names for values, values that change, and the kind of each value

  3. BOSS
    A receipt

    Prices, a discount and tax, turned into a printed total

Read the unit guide

A Rust program is a list of instructions. It starts at fn main() {, runs the lines between the braces from top to bottom, and stops at the closing }. Each instruction ends with a semicolon. Before anything runs, a tool called the compiler reads the whole program and refuses to start it if something is wrong.

println! puts a line on the screen. The text between the quotes is printed as it is, except for each {}: that is a gap, filled with a value given after the comma. A name can go straight into the gap, as in {total}, and {total:.2} shows it with two digits after the point.

Rust keeps whole numbers and decimals apart. 7 / 2 is 3, because two whole numbers give a whole number, and 7 % 2 is the 1 left over. 7.0 / 2.0 is 3.5. Multiplication and division happen before addition and subtraction, and brackets go first.

let gives a value a name: a variable. A plain let can never be changed; let mut can. A second let with the same name makes a brand-new variable that hides the old one, which is called shadowing.

Every value has a type: i32 for whole numbers, f64 for decimals, bool for true or false, char for one character. Rust works the type out for you, and never mixes two types silently. as converts on purpose: count as f64.

The classic first mistake is fighting the compiler instead of reading it. Its first line says what is wrong, the arrow says where, and the help line often contains the fix.

Unit 02 · 3 lessons

Decisions and loops

Make a program choose between paths and repeat work, and trace what it does by hand

  1. 01Conditions
  2. 02Loops
  3. BOSSFizzBuzz and friends
Unit prize
  1. 01
    Conditions

    Comparisons, and, or, not, if, else and a first match

  2. 02
    Loops

    while, for, loop, break and continue, traced round by round

  3. BOSS
    FizzBuzz and friends

    Loops and conditions together, and the off-by-one error

Read the unit guide

A comparison asks a question and answers with a bool: true or false. The six comparisons are ==, !=, <, >, <= and >=. One = stores a value; two compare. && means and, || means or, ! means not.

if runs its braces only when the test is true, and else gives the other path. In a chain of else if, Rust takes the first test that is true and skips the rest, so test the most special case first. An if can also produce a value: let price = if age < 12 { 5 } else { 9 };. match compares one value with a list of patterns, and _ catches everything else.

A loop repeats its braces. while repeats as long as a test is true. for i in 1..4 hands out 1, 2 and 3: the end of a range is left out, and 1..=4 includes it. loop repeats until a break; continue jumps to the next round.

The key pattern is the running total: make a let mut variable before the loop, change it inside, read it after. To understand any loop, trace it: write down the value of each variable after every round.

Three small tools solve a surprising number of problems. n % d == 0 asks whether d divides n. n % 10 is the last digit of n, and n / 10 removes it.

The classic pitfall is the off-by-one error: a loop that runs once too often or once too few, usually because of .. against ..= or < against <=. Always check the first and the last round by hand.

Unit 03 · 3 lessons

Functions and ownership

Write small functions, and know who owns each value they touch

  1. 01Defining functions
  2. 02Ownership
  3. BOSSA text toolkit
Unit prize
  1. 01
    Defining functions

    Parameters, results, and one function calling another

  2. 02
    Ownership

    Who owns a value, when it moves, and how to lend it

  3. BOSS
    A text toolkit

    Small functions that borrow text and return new text, each one checked

Read the unit guide

A function is a named piece of work. fn double(n: i32) -> i32 { n * 2 } has a name, a parameter with its type, the type of its result after ->, and a body. Calling double(4) runs the body with n as 4. The result is the last line of the body, written without a semicolon; return is for leaving early.

Small functions that each do one job can be combined: one function may call another. Check each with assert_eq!(call, expected), which stays silent when the two are equal and stops the program, showing both, when they are not.

Text comes in two kinds. "hello" written in the code is a &str: fixed text that you can look at. A String is text the program owns and can grow, made with String::from("hello") or String::new().

Every value has exactly one owner, the variable that holds it, and the value is dropped at the closing brace of its owner's scope. Assigning a String to another name, or passing it to a function, moves it: the old name is finished and the compiler rejects any later use. Numbers, bool and char are simply copied instead. clone makes a real second copy of a String.

Most functions should borrow instead of taking. &word lends a value without giving it away, and a parameter of type &str accepts both a literal and a borrowed String. A function that makes new text returns a String.

The classic pitfall is the stray semicolon on the last line of a function: n * 2; hands back nothing, and the compiler says it expected i32 and found ().

Unit 04 · 3 lessons

Collections

Keep many values under one name, look them up, and lend them out safely

  1. 01Vectors and borrowing
  2. 02Hash maps and tuples
  3. BOSSA word counter
Unit prize
  1. 01
    Vectors and borrowing

    A list of values, safe lookups, and many readers or one writer

  2. 02
    Hash maps and tuples

    Values found by key, counting with entry, and values that travel in pairs

  3. BOSS
    A word counter

    Text split into words, counted in a map, sorted and reported

Read the unit guide

A vector, Vec, holds many values of one type in order. vec![70, 85] makes one, push adds to the end, len() counts the items, and v[0] is the first: positions, called indexes, start at 0, so the last index is len() - 1. Indexing past the end stops the program; v.get(i) answers Some(value) or None instead.

Ownership applies to collections as a whole. for x in v hands the vector over and it is gone afterwards; for x in &v only borrows it. The rule for loans is many readers or one writer: any number of & loans may exist together, but a &mut loan, which allows changes, must be the only one. A slice, &v[1..3], is a borrowed view of part of a vector.

A HashMap stores pairs and finds a value by its key instead of its position. insert adds or replaces a pair, and get returns an Option because the key may be missing. The counting pattern is *map.entry(key).or_insert(0) += 1;. A map keeps no order.

A tuple groups a few values in round brackets, such as ("tea", 3). Read the parts with .0 and .1, or unpack them all at once: let (name, qty) = pair;. Tuples compare by their first part, then their second.

To rank what a map has counted, copy the pairs into a vector with the count first, then sort() and reverse() it.

The classic pitfall is holding a loan across a change: keep a &v[0] in a variable, push to the vector, then use the variable. The compiler refuses, because the push may move every item to a new place in memory.

Unit 05 · 3 lessons

Your own types

Model a problem with structs and enums, and let the compiler hold you to the model

  1. 01Structs and methods
  2. 02Enums and match
  3. BOSSAn inventory
Unit prize
  1. 01
    Structs and methods

    Named fields, impl, &self and &mut self, new

  2. 02
    Enums and match

    A value that is exactly one of a few things, and Option

  3. BOSS
    An inventory

    Items as structs, stock states as an enum, updates through &mut

Read the unit guide

Until now every value had a type that came with the language: a number, some text, a vector. A struct is a type you design. It groups named fields, so pen.count says what it is where item.1 did not. To build one you give every field a value. The compiler refuses a struct that is half built.

Functions that belong to a struct go in an impl block and are called methods. The first parameter says what the method may do with the value: &self reads it, &mut self changes it. These are the same borrows you already know, so the same rule holds: to call a &mut self method, the variable must be let mut. A function without self, such as new, is called on the type with ::.

An enum is a type that is exactly one of the variants you list. Use it whenever the honest answer to "what can this be?" is a short list: red, yellow or green; out, low or fine. A variant can carry data of its own, and that data can only be reached in the match arm for that variant.

match must cover every variant. That sounds strict, and it is the point: when you add a variant later, the compiler shows you every match that has to change. Text and numbers give no such help. A misspelt word in a String is a quiet bug; a misspelt variant does not compile.

Option is an enum from the standard library: Some(value) or None. It replaces the "null" of other languages. Anything that might find nothing returns one, and you cannot use the value inside until match or if let has checked that it is there.

The pitfall is keeping a rule outside the type. If any line of the program can write pen.count -= 5, sooner or later one will sell pens the shop does not have. Put the rule in a method, such as sell, and make that method the way to change the count.

Unit 06 · 3 lessons

Errors and modules

Treat failure as a value the caller cannot forget, and split a program into modules

  1. 01Result
  2. 02Your own errors and modules
  3. BOSSA bank
Unit prize
  1. 01
    Result

    Ok and Err, match, the ? operator, and when unwrap is fine

  2. 02
    Your own errors and modules

    An error enum, From for ?, and mod, pub and use

  3. BOSS
    A bank

    Accounts, transfers and a history, with every rule a Result

Read the unit guide

Things go wrong: text is not a number, an account is empty, a file is missing. Rust has no hidden way of failing. A function that can fail says so in its return type, Result, an enum with two variants: Ok(value) when it worked and Err(error) when it did not. The caller gets one value and has to open it to reach the answer.

There are three ways to open a Result. match handles both cases on the spot. The ? operator says "give me the value, or return this error to my caller right now", and works only in a function that itself returns a Result (or an Option). unwrap and expect say "give me the value or crash". Use those only where an error would be a bug in your own code, never on input from outside.

Text makes a poor error. The caller ends up comparing strings, and a typo in one of them compiles. List the ways a function can fail as an enum and use it as the error type. Now the caller can match on the exact problem and the compiler checks the spelling and the coverage.

When a function meets several kinds of error, ? needs to turn each of them into the one error type the function returns. An impl From<TheirError> for MyError block teaches it how. You write the conversion once.

A module, mod name { ... }, is a named box for related code. Everything in it is private unless marked pub, and that goes for struct fields too. Reach a public item by its path, shop::tax, or bring the name in with use. Privacy is how a type protects its rules: if balance is private, only the bank's own methods can change it.

The pitfall is doing things in the wrong order around ?. Every ? is a possible exit from the function. Whatever ran before it stays done. In a transfer, take the money out first: if that fails, nothing has happened yet.

Unit 07 · 3 lessons

Traits and generics

Write one piece of code that works for many types, and say exactly what it needs from them

  1. 01Traits
  2. 02Generics and lifetimes
  3. BOSSA log report
Unit prize
  1. 01
    Traits

    A promise a type makes, default methods, Display and the derives

  2. 02
    Generics and lifetimes

    A placeholder for a type, trait bounds, and the lifetime the compiler asks for

  3. BOSS
    A log report

    Lines of text parsed into structs, then counted, grouped and ranked

Read the unit guide

Two types can look alike and still be strangers to the compiler. A function that takes a &Dog will not take a &Cat, even if both have a speak method. A trait fixes that. It names something a type can do and lists the methods that go with it. impl Speak for Cat is where a type keeps the promise, and the compiler checks that every listed method is there.

Once a trait exists, code can ask for it and nothing more. A parameter of type &impl Speak accepts any type that carries the trait. A trait method may have a default body, which every such type gets for free and may replace.

The standard library is full of traits, and you have been using them. {:?} needs Debug, {} needs Display, == needs PartialEq, < needs PartialOrd, .clone() needs Clone. For most of these, #[derive(...)] above a struct or enum has the compiler write the obvious version. Display you write yourself, because only you know how the value should look to a user.

Generics put a placeholder where a type would go. fn swap<T>(a: T, b: T) works for any T, and Vec<T>, Option<T> and Result<T, E> are built the same way. Inside a generic function you may do only what every possible T allows, which is almost nothing. A bound such as <T: PartialOrd> narrows T to types that carry a trait, and unlocks that trait's abilities.

A lifetime name such as 'a appears when a function returns a borrow and has more than one borrowed parameter. It answers one question for the compiler: which of the inputs is the result borrowed from? With one borrowed parameter there is nothing to ask, and you write nothing.

The pitfall is reaching for these tools too early. Write the plain version for one type first. When a second type needs the same code, that is the moment for a trait or a <T>.

Unit 08 · 3 lessons

Hero

Process data with iterator chains, share it safely, even between threads, and build a whole program

  1. 01Closures and iterators
  2. 02Sharing and threads
  3. BOSSA task manager
Unit prize
  1. 01
    Closures and iterators

    Functions written in place, and chains of map, filter, sum and collect

  2. 02
    Sharing and threads

    Box, Rc and RefCell in outline, then threads, locks and channels

  3. BOSS
    A task manager

    One program from an empty file: model, commands, errors, a report and tests

Read the unit guide

A closure is a function written in place, without a name: |x| x * 2. The inputs sit between the bars and the body follows. Unlike a fn, a closure can use the variables around it. That makes it the natural thing to hand to other code: "here is what to do with each item".

Iterators are where closures pay off. .iter() walks over a collection, map changes each item, filter keeps some, and sum, count or collect finish the job. The chain reads top to bottom like a recipe. It is also lazy: map and filter do nothing at all until a finishing step asks for items.

One value, one owner is the rule so far. Sometimes that is too strict. Box keeps a value elsewhere in memory and holds on to it with a small fixed-size handle. Rc lets a value have several owners and counts them. RefCell moves the borrowing check from compile time to run time, for data that is shared and changed.

A thread is a second line of work running at the same time as the first. thread::spawn starts one from a closure, and move gives that closure ownership of what it uses. Between threads, Arc replaces Rc, and a Mutex lets one thread at a time touch a value. A channel carries values from one thread to another. The compiler refuses programs in which two threads could change the same data unguarded, so that whole family of bugs never runs.

The capstone builds a task manager from an empty file: the data model first, then commands, errors as Result, a report with iterator chains, and tests. Then a new feature arrives, and the compiler lists every place that must change.

After this course, the Rust roadmap covers the same language faster and deeper. Outside the app, install Rust, run cargo new, and build something small of your own: cargo is the tool that builds, runs and tests Rust projects.

Learn Rust: Zero to Hero 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