Module 01 — Setup, Cargo & Hello World
Goal
Install the toolchain, learn what happens between a .rs file and a running binary, and get fluent with Cargo — the tool you will live inside for the rest of the course.
Start here — what this module is really about
Before any code: Rust is a language where a program is translated once, completely, before it ever runs. That single fact explains almost everything you will meet in this module.
In Python or JavaScript, the thing that runs your code is a program called an interpreter, and it reads your source line by line as it goes. Mistakes surface when execution reaches them — sometimes minutes into a run, sometimes only for one unlucky user. Rust instead hands your source to a compiler (rustc), which reads all of it, checks all of it, and produces a single executable file of machine instructions. If anything is wrong, you get no executable at all.
So there are two distinct moments in a Rust project, and this course refers to both constantly:
- Compile time — when
rustcis reading and checking your code. Errors here cost you nothing but time. - Runtime — when the finished executable is running on a real machine, doing the actual work.
Rust's whole design is about moving problems from the second moment to the first.
The other thing this module gives you is Cargo. You will type cargo more than any other word for the rest of the course. It is not part of the language — it is the tool that creates projects, fetches libraries, compiles, runs and tests them, so you never invoke the compiler by hand.
The one sentence to remember: nothing runs until everything checks.
Learning objectives
- Install and manage Rust with
rustup - Explain Rust's compilation model and how it differs from interpreted languages
- Create, build, run, and test a project with Cargo
- Read the anatomy of a minimal Rust program
- Know what a macro is (at a surface level) and why
println!has a!
1.1 What Rust is, in one paragraph
Rust is a statically typed, ahead-of-time compiled systems language with no garbage collector and no runtime. It gives you C-level control over memory and performance while guaranteeing — at compile time — that your program has no use-after-free, no double free, no null dereference, and no data races. It buys that guarantee with a concept called ownership, enforced by a component of the compiler called the borrow checker. Everything hard and everything wonderful about Rust flows from that trade.
TS ↔ Rust: TypeScript's types vanish at runtime; they're a linting layer over
JavaScript. Rust's types are the program. There is no any, no runtime type coercion,
and no way for a value to be undefined.
Analogy — the pre-flight checklist
An interpreted language is a road trip: start driving and find out about the flat tyre when you feel it. Rust is a pre-flight checklist — nothing leaves the ground until every item is signed off, which is tedious at the gate and the reason nobody troubleshoots hydraulics mid-air. The compiler's refusal to build is not it being difficult; it is the checklist doing the only job it has.
1.2 Installing the toolchain
Install rustup, the official toolchain manager:
# macOS / Linux
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Windows: download and run rustup-init.exe from https://rustup.rsThen restart your shell and verify:
rustc --version # the compiler, e.g. rustc 1.8x.0
cargo --version # the build tool, e.g. cargo 1.8x.0
rustup --version # the toolchain managerWhat rustup installed
| Tool | Purpose |
|---|---|
rustc | The compiler. You will rarely invoke it directly. |
cargo | Build system, package manager, test runner, doc generator. Your daily driver. |
rustfmt | Auto-formatter. Run cargo fmt. Non-negotiable in real projects. |
clippy | Linter with ~700 lints. Run cargo clippy. Teaches you idioms. |
rust-docs | Offline standard library docs. Run rustup doc --std. |
Useful rustup commands:
rustup update # update to the latest stable Rust
rustup component add clippy rustfmt
rustup toolchain install nightly
rustup default stable # switch default toolchainEditor setup
Install rust-analyzer (VS Code extension, or LSP plugin for your editor). It gives inline type hints, instant error squiggles, and one-click "apply compiler suggestion". Working without it is like writing TypeScript in Notepad — possible, painful.
1.3 Hello, world — the long way
Create hello.rs:
fn main() {
println!("Hello, world!");
}Compile and run manually:
rustc hello.rs # produces an executable named `hello` (hello.exe on Windows)
./hello # Hello, world!Anatomy
fn main() {
//^^ ^^^^ ^^
//| | |__ body, delimited by braces
//| |_______ the name `main`: the entry point of every executable
//|___________ `fn` keyword: declares a function
println!("Hello, world!");
// ^^^^^^^^ ^^^^^^^^^^^^^^^ ^
// | | |__ statements end with a semicolon
// | |__________________ a string literal, type &'static str
// |___________________________ a MACRO (note the `!`), not a function
}Why println! and not println
A macro is code that runs at compile time and expands into more code. println!
needs to accept a variable number of arguments of differing types and validate the
format string at compile time — a plain function can't do that in Rust, because Rust
has no variadic functions and no runtime reflection.
fn main() {
let name = "Ferris";
let legs = 10;
println!("{name} has {legs} legs"); // inline captured identifiers
println!("{} has {} legs", name, legs); // positional
println!("{0} {1} {0}", "a", "b"); // indexed -> "a b a"
println!("{:?}", (1, "two")); // debug formatting
println!("{:>8.2}", 3.14159); // width 8, right-aligned, 2 decimals
}If you get the argument count wrong, the program does not compile. That's the point.
Mental model
The ! means "this is expanded before compilation." When you see
! on a call, expect flexible syntax and compile-time checking.
Reading that program one piece at a time
Four lines, and every one of them is a convention worth knowing:
fnstarts a function — a named block of code. Every Rust program begins at a function calledmain, so the name is not decorative; the compiler looks for exactly that.()is where a function's inputs would go.maintakes none, so the parentheses are empty — but they are still required, because that is how Rust writes "this is a function".- The braces wrap the function's body: everything it does. Indentation is for humans here; the braces are what the compiler reads.
println!("Hello, world!");prints a line. The!matters: it meansprintln!is a macro, not a function. For now, take "macro" to mean code that writes code before compilation begins — which is how it can check your text formatting at compile time, something a normal function could never do. The;ends the statement.
If you type this and get an error, that is the module working as intended — read §1.6 and treat it as your first lesson rather than a setback.
1.4 The compilation model
main.rs ──► [ parse ] ──► [ type check ] ──► [ borrow check ] ──► [ optimize ] ──► binary
▲
this stage is unique to Rust
Key consequences:
- There is no runtime interpreter. The binary is standalone machine code; it does not need Rust installed on the target machine.
- Errors are front-loaded. Rust compiles slower than Go and much slower than interpreting JS, because it does far more work up front. In exchange, a large class of bugs cannot reach production.
- Zero-cost abstractions. Iterators, generics, and traits are compiled away. A
forloop over.iter().map().filter()typically emits the same assembly as a hand-written index loop.
There are two build profiles:
cargo build # debug: fast to compile, slow to run, overflow checks ON
cargo build --release # release: slow to compile, fast to run, optimizedA debug build can easily be 10–100× slower than release. Never benchmark a debug build.
Analogy — recipe vs. finished meal
An interpreted script is a chef reading your recipe aloud line by line while cooking, every single service. Compiling is cooking the dish once, perfectly, and shipping it frozen: all the reading, checking and deciding happened in the kitchen, so the customer's microwave does nothing but heat. That is why a Rust binary needs no interpreter, no runtime and no node_modules at the table.
1.5 Cargo: your real interface to Rust
You will almost never call rustc. Create a project:
cargo new hello_cargo
cd hello_cargoLayout:
hello_cargo/
├── Cargo.toml # manifest: name, version, edition, dependencies
├── Cargo.lock # exact resolved dependency versions (commit this for binaries)
├── .gitignore
└── src/
└── main.rs # crate root for a binary
Cargo.toml:
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
[dependencies]TS ↔ Rust: Cargo.toml ≈ package.json, Cargo.lock ≈ package-lock.json,
crates.io ≈ npm, cargo ≈ npm + tsc + jest + eslint + prettier in one binary.
The commands you'll use daily
cargo new my_proj # new binary project
cargo new my_lib --lib # new library project
cargo init # initialize in an existing directory
cargo check # type/borrow check WITHOUT producing a binary — very fast
cargo build # compile to target/debug/
cargo run # build + run
cargo run -- arg1 arg2 # pass args to your program
cargo build --release # optimized build in target/release/
cargo test # run all tests
cargo fmt # format all code
cargo clippy # lint
cargo doc --open # build and open your project's API docs
cargo add serde # add a dependency (edits Cargo.toml)
cargo update # update dependencies within semver bounds
cargo clean # delete target/Workflow tip
Keep cargo check in a watch loop while you write
(cargo install cargo-watch then cargo watch -c -x check). It's 3–10× faster than
cargo build because it skips code generation.
Adding a dependency
cargo add randuse rand::Rng;
fn main() {
let n: u8 = rand::thread_rng().gen_range(1..=100);
println!("Your number is {n}");
}use brings a path into scope — it is not an import that loads code at runtime; all
linking is static and resolved at compile time.
The five Cargo commands that cover 95% of the work
You do not need to memorise Cargo. You need these five, and you will have them by module 03 from repetition alone:
| Command | What it does | When you reach for it |
|---|---|---|
cargo new name | Creates a project folder, ready to build | Starting anything |
cargo run | Compiles and runs it | Every few minutes, all course long |
cargo check | Compiles without producing an executable | When you only want to know "does this compile?" — much faster |
cargo test | Runs your tests | From module 16 onward, constantly |
cargo build --release | Builds the optimised version | Only when you care about speed |
The one people miss is cargo check. While you are learning ownership and borrowing you will compile far more often than you run, and check gives you the compiler's verdict in a fraction of the time.
Analogy — Cargo is the site foreman
rustc is a single skilled bricklayer: give it exact instructions and it lays exactly those bricks. Cargo is the foreman who knows the whole build — which materials to order, in what order the trades go in, where the finished thing gets stored, and how to do it identically next Tuesday. You can direct the bricklayer yourself; on any real project you talk to the foreman.
1.6 Reading a compiler error
Deliberately break something:
fn main() {
let x: i32 = "five";
}error[E0308]: mismatched types
--> src/main.rs:2:18
|
2 | let x: i32 = "five";
| --- ^^^^^^ expected `i32`, found `&str`
| |
| expected due to this
Anatomy of the message:
error[E0308]— a stable error code.rustc --explain E0308prints a full tutorial.--> file:line:column— exact location.- The underline shows what is wrong; the secondary underline shows why Rust expected what it expected.
Rust errors are unusually good. Reading them carefully is the single highest-return habit in this course.
How to actually read a Rust error
Rust's error messages are unusually long, and beginners skim them. Do the opposite — they are written to be read straight through, and they have a fixed shape:
- The first line names the error code and states the problem in one sentence, e.g. error[E0382]: borrow of moved value.
- The arrow line (
-->) gives file, line and column. That is where the compiler noticed, which is not always where you made the mistake. - The code excerpt underlines the relevant spans, often several, each with its own note: this is where the value came from, this is where it moved, this is where you tried to use it. Read all of them — the story is usually complete right there.
help:proposes a concrete fix. It is frequently correct and can often be applied verbatim.note:explains the rule behind the refusal — the part that actually teaches you something.
And when you want more than the message, rustc --explain E0382 prints a full page on that specific error, with examples. Every error code in this course can be looked up that way.
Do not paste the error into a search engine before reading it to the end. Nine times out of ten the answer is in the help: line.
Analogy — the compiler as a code reviewer
Most compilers report a fault like a dashboard warning light: something is wrong, good luck. Rust's reads like a patient senior reviewer — here is the line, here is what I expected, here is what I found, and here is the change I would make. Learn to read the whole message, help: and note: included; skipping to the red line is skipping the review.
Jargon buster
Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.
| Term | In plain English |
|---|---|
| compiler | The program that translates your source into an executable, checking all of it first. Rust's is called rustc. |
| compile time | The moment when your code is being checked and translated. Errors caught here never reach a user. |
| runtime | The moment when the finished program is actually running. |
| binary / executable | The single file the compiler produces, containing machine instructions your operating system can run directly. |
| crate | A Rust package — one unit of code that gets compiled. Your project is a crate; so is each library you depend on. |
| Cargo | Rust's project tool: creates projects, downloads dependencies, compiles, runs and tests them. |
| macro | Code that generates code before compilation. Called with a !, like println!. |
| toolchain | The set of tools for one Rust version — compiler, Cargo, formatter, docs. Managed by rustup. |
If you get stuck
The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.
| What you see | What it means | What to do |
|---|---|---|
command not found: cargo | Your shell cannot see the Rust tools. | Close and reopen the terminal. If it persists, rustup did not add ~/.cargo/bin to your PATH — re-run the installer. |
error: expected one of ..., found ... | A syntax mistake — usually a missing ;, ) or }. | Look at the line the arrow points to and the line above it; a missing semicolon is reported on the following line. |
error[E0425]: cannot find value ... in this scope | You used a name the compiler has never seen. | Check spelling and capitalisation. Rust is case-sensitive, and a typo in a variable name looks exactly like this. |
warning: unused variable | Not an error — the code compiled fine. | Prefix the name with an underscore (_x) to say the unused value is deliberate. |
Now make it stick: work through the drills for this module, then carry on to Module 02 — Variables, Types & Memory Basics.
