Introduction to Rust

Introduction to Rust in Rust: Picture a vast warehouse full of crates. Every crate holds something a program needs: a customer record, a decoded image, a…

The Analogy: The Warehouse With Numbered Keys

Picture a vast warehouse full of crates. Every crate holds something a program needs: a customer record, a decoded image, a buffer of network bytes. To work with a crate you need its key. The interesting question in any programming language is not "how do I get a key" but "what stops two people from emptying the same crate at the same time, and who is responsible for sweeping up when a crate is no longer needed."

In an older systems language like C, the warehouse hands out photocopied keys freely. It is fast and it is flexible, and it is also how you end up with two workers reaching into one crate while a third has already hauled it to the dumpster. Nothing at the front desk checks. The mistake is not discovered on the day it is made; it is discovered six months later, in production, as a corrupted invoice or a security advisory.

In a garbage-collected language like Java or Python, the warehouse solves this by employing a janitor. You may copy keys all you like, and the janitor wanders the aisles deciding which crates nobody can reach any more and removing them. This is genuinely safer, and you pay for it in two coins: the janitor needs memory to do the bookkeeping, and every so often the janitor blows a whistle and all work stops until the sweep is finished.

Rust takes a third road. There is no janitor, and there are no photocopiers. Instead the front desk keeps a ledger: every crate has exactly one owner at a time, and the desk clerk refuses to let you walk away with a key that is already someone else's. If you want two people to read a crate at once, you ask for read passes, and the clerk will issue as many as you like, but only while nobody holds the single write pass. The remarkable part is when this checking happens: not at run time, but while the building plans are being approved. The clerk is the compiler. If the plan does not add up, the program never gets built, so there is nothing to pay for at run time. That is the whole bargain of Rust: the arguments happen at compile time so that they do not happen at three in the morning.


Syntax or Core Structure

Every Rust executable starts at a function called main. Here is the entire program:

fn main() {
    println!("Hello, world!");
}

Output:

Hello, world!

Four things in that tiny program are worth naming now, because they come back in every lesson. fn declares a function. main is the entry point the linker looks for. The braces delimit a block, which in Rust is also an expression. And println! ends in an exclamation mark because it is a macro, not a function: it is expanded by the compiler, which is how it can typecheck a format string against its arguments at compile time.

A slightly larger program introduces bindings and formatting:

fn main() {
    let name = "Rustacean";
    let mut visits = 1;
    visits += 1;

    println!("Welcome, {name}!");
    println!("You have been here {visits} times.");
    println!("{} + {} = {}", 2, 3, 2 + 3);
    println!("[{:>8.3}]", 3.14159_f64);
}

Output:

Welcome, Rustacean!
You have been here 2 times.
2 + 3 = 5
[   3.142]

let introduces a binding, and a binding is immutable by default. visits needed mut because the next line changes it; name did not. The {name} form, where the variable is named inside the braces, is called an inline format argument and needs Rust 1.58 or newer. {:>8.3} says right-align in a field of eight characters with three digits after the decimal point, which is why the output has three leading spaces before 3.142.


Technical Depth: What "Safe Without a Garbage Collector" Means

Where each language pays

Every language has to answer the same two questions, and the answers cost something.

LanguageMemory reclaimed byRun-time overheadUse-after-free possibleData race possible
C / C++you, by handnoneyesyes
Java / C#tracing garbage collectorcollector pauses plus heap headroomnoyes
Pythonreference counting plus a cycle collectorinterpreter plus collectornono corruption, because the GIL serialises bytecode, but logical races remain
Gotracing garbage collectorshort collector pausesnoyes, and the race detector is opt-in
Rustscope, decided at compile timenoneno, in safe Rustno, in safe Rust

The last row is the claim that makes Rust unusual, and the phrase "decided at compile time" is the load-bearing part. The compiler works out where each value stops being used and emits the cleanup call itself. There is no bookkeeping left over at run time, which is why a Rust binary can go into a microcontroller, a kernel module, or a browser engine.

Which checks run when

"Rust is safe" is too coarse to be useful. These are the specific guarantees and the specific moment each one is enforced.

GuaranteeEnforced byWhen
every value has exactly one ownerownership rulescompile time
no reference outlives what it points atborrow checker and lifetimescompile time
never a shared reference and a mutable one at onceborrow checkercompile time
a value moved between threads is safe to movethe Send traitcompile time
a value shared between threads is safe to sharethe Sync traitcompile time
slice and array indexes are in boundsbounds checkrun time, panics on failure
integer arithmetic did not overflowoverflow checkrun time in debug builds; wraps silently in release

That last row surprises people, so it is worth stating plainly: i32::MAX + 1 panics under cargo run and quietly becomes i32::MIN under cargo run --release. If you need a defined answer in both, ask for it with checked_add, saturating_add, or wrapping_add.

What Rust does not protect you from

An honest introduction has to include this list, because "safe" is a narrow technical word here. It means no undefined behaviour from memory misuse. It does not mean correct.

  • Logic bugs. A borrow-checked program can still bill the wrong customer.
  • Deadlocks. Two threads each waiting on the other's lock compiles perfectly and hangs forever.
  • Memory leaks. Two Rc values pointing at each other form a cycle whose count never reaches zero, and std::mem::forget leaks on purpose. Leaks are considered safe: they waste memory without corrupting it.
  • Panics. An index out of bounds, an unwrap on None, or an explicit panic! will abort the thread. Safe, but not running.
  • Integer overflow in release mode, as noted above.
  • Anything inside unsafe. The keyword does not disable the compiler; it moves responsibility for a short list of rules from the compiler to you.

The tools you will actually type

ToolJobTypical command
rustupinstalls toolchains and switches between stable, beta, and nightlyrustup update
rustcthe compiler itself; you rarely call it directlyrustc main.rs
cargobuild system, dependency manager, and test runner in onecargo build, cargo test
clippyseveral hundred extra lints beyond the compiler's owncargo clippy
rustfmtthe canonical formatter, so style arguments endcargo fmt
rust-analyzerthe language server that powers editor completionruns in your editor

Installing rustup gets you rustc and cargo; clippy and rustfmt ship with the default profile. There is no separate build tool to choose, no Makefile to write, and no debate about the project layout, which removes an entire category of first-day friction.

Editions, and why they are not versions

Rust promises that code which compiles on a stable release keeps compiling on later ones. That promise makes it hard to reclaim a keyword or change a default. Editions are the escape hatch: an opt-in, per-crate label in Cargo.toml.

EditionNotable change
2015the original; extern crate still required
2018new module paths, dyn Trait, async/await reserved
2021closures capture individual fields, IntoIterator for arrays
2024tighter unsafe rules, new gen reservation, lifetime-capture changes

Crucially, editions are per crate and they interoperate. A 2024-edition binary can depend on a 2015-edition library, so the ecosystem never has to migrate all at once. This is the mechanism behind the fact that Rust has had no "Rust 2" and no Python-3-style split.


Real World Example: Summarising a Batch of Sensor Readings

Enough philosophy. Here is a program of the size you actually write on day one: it takes a batch of temperature readings and reports the shape of the data.

fn main() {
    let readings_c = vec![21.5, 23.0, 19.75, 25.25, 22.0];

    let count = readings_c.len();
    let sum: f64 = readings_c.iter().sum();
    let mean = sum / count as f64;

    let mut min = readings_c[0];
    let mut max = readings_c[0];
    for &r in &readings_c {
        if r < min {
            min = r;
        }
        if r > max {
            max = r;
        }
    }

    println!("samples: {count}");
    println!("min:     {min:.2} C");
    println!("max:     {max:.2} C");
    println!("mean:    {mean:.2} C  ({:.1} F)", mean * 9.0 / 5.0 + 32.0);
    println!("range:   {:.2} C", max - min);

    let warm: Vec<f64> = readings_c
        .iter()
        .copied()
        .filter(|&r| r > mean)
        .collect();
    println!("above mean: {warm:?}");
}

Output:

samples: 5
min:     19.75 C
max:     25.25 C
mean:    22.30 C  (72.1 F)
range:   5.50 C
above mean: [23.0, 25.25]

Two lines in that program look like noise and are actually the language showing its hand. count as f64 is there because Rust performs no implicit numeric conversion at all: len() gives a usize, and dividing a f64 by a usize is not a thing you can do by accident. And let sum: f64 needs its annotation because sum() is generic over what it produces; the annotation is how the compiler picks the implementation. Beginners read these as bureaucracy. They are the same mechanism that later stops you from silently truncating a 64-bit file offset into a 32-bit integer.

for &r in &readings_c is the ownership system in miniature. &readings_c borrows the vector rather than consuming it, so the vector is still alive on the next line. The &r in the pattern position destructures each &f64 back into an f64, which is possible because f64 is cheap to copy. Had the loop been written for r in readings_c, the vector would have been moved into the loop and every later use of readings_c would be a compile error reading borrow of moved value. That error is the single most common first-week experience in Rust, and it is worth meeting it here, in five lines, rather than in five hundred.

The final block is an iterator chain, and it is lazy: iter(), copied(), and filter() build a description of work, and collect() is what actually runs it. The type of the result is not inferred from the chain but from the annotation Vec<f64>, because collect() can build a Vec, a HashSet, a String, or anything else that implements FromIterator. Despite reading like a functional pipeline, this compiles to essentially the same machine code as the hand-written for loop above it, which is the property Rust calls a zero-cost abstraction.

Now notice what is not in the program. The vector allocated a buffer on the heap, and nothing frees it. There is no free, no delete, no try/finally, and no collector deciding when to sweep. The compiler determined that readings_c stops being used at the closing brace of main and emitted the deallocation there, at a point it could prove was correct. That is the entire pitch of this course in one program: you write down the shape of the data and its lifetime falls out of the code, checked before the binary exists. The next lesson turns to cargo, the tool that turns files like this one into projects.


Common Mistakes

  1. Sprinkling .clone() to silence the borrow checker. It compiles, and it converts a design question into a hidden allocation. When the checker complains, the first move is to ask whether the function needs to own the data or only read it; nine times out of ten changing a parameter to &T is the real fix.
  2. Expecting numeric types to convert themselves. let x: u64 = some_u32; fails, and so does adding a usize to an i32. Rust wants the cast written down, with as for quick conversions or try_into() when the conversion can lose information.
  3. Forgetting mut and reading the error as a bug. cannot assign twice to immutable variable is not the compiler being strict for its own sake; immutable-by-default is what lets it reason about aliasing later.
  4. Treating println! as a function. You cannot pass it around, and the format string must be a literal, not a variable, because it is parsed at compile time. println!(user_input) will not compile, which is also why Rust has no format-string vulnerability.
  5. Reading "memory safe" as "bug free". Safety here means no undefined behaviour from memory misuse. Deadlocks, leaked Rc cycles, panics, and wrong answers are all still available to you.
  6. Benchmarking a debug build. Unoptimised Rust can be ten times slower or worse, and overflow checks are on. Any performance claim must come from cargo run --release or cargo bench.
  7. Thinking unsafe turns the checks off. Inside an unsafe block the borrow checker, the type system, and every other guarantee still apply. It unlocks exactly five extra abilities, such as dereferencing a raw pointer, and it makes you responsible for the rules the compiler can no longer verify.
  8. Installing the compiler from a distribution package. Repository versions are often many releases behind, which produces baffling errors when a crate needs a feature that stabilised last year. Use rustup, which manages toolchains per project.
  9. Assuming String and &str are one type. They are related but distinct: one owns a heap buffer, the other borrows a view of text. Meeting that distinction early makes the collections module far less surprising.

Best Practices

  • Install with rustup and update deliberately. rustup update moves you forward on your schedule, and rust-toolchain.toml in a repository pins the exact version for everyone on the team.
  • Read the entire error, not the first line. Rust's diagnostics include help: and note: lines that usually contain the fix verbatim, and rustc --explain E0382 prints a page-long explanation of any error code.
  • Put cargo fmt and cargo clippy in the loop. Formatting stops being a discussion and Clippy teaches idiom faster than any tutorial, because it explains the why on every lint.
  • Default to immutable and add mut only when the compiler insists. The result is that anything mutable in your code is visibly, deliberately mutable.
  • Prefer borrowing over cloning in function signatures. Take &str rather than String and &[T] rather than Vec<T> unless the function genuinely needs ownership; callers can then pass either.
  • Measure only in release mode, and say which mode a number came from. A benchmark without its build profile is not a number, it is a rumour.
  • Reach for checked_add, saturating_sub, or wrapping_mul at trust boundaries. Where input comes from a user or a network, be explicit about what overflow should mean instead of relying on the build profile.
  • Keep unsafe blocks as small as the operation requires, and write the invariant above them in a comment. A three-line unsafe block with a paragraph of justification is reviewable; a hundred-line one is not.

Practice Exercises

  1. Install and confirm. Install the toolchain with rustup, then print the versions of rustc, cargo, and clippy. Write down which edition a brand-new cargo new project selects for you.
  2. Make the compiler complain, on purpose. Take the sensor program above and change for &r in &readings_c to for r in readings_c. Compile it, read the whole error, then run rustc --explain on the error code it reports and summarise the explanation in two sentences.
  3. Extend the summary. Add a median to the report. You will need a sorted copy of the data, which means deciding whether to sort a clone or to sort a mutable vector, and handling the even-length case where the median is the mean of the two middle values. Verify your output by hand against the five readings.
  4. Watch overflow change behaviour. Write a program that adds 1 to i32::MAX and prints the result. Run it with cargo run and then with cargo run --release, record both outcomes, and finally rewrite the addition with checked_add so that the program behaves identically under both profiles.