Why Rust exists
For fifty years, programmers who needed raw speed and close control of the machine have reached for C and, later, C++. Operating systems, databases, browsers, game engines and the firmware in your router are written in them. They let you decide exactly where every byte lives and when it is freed, and the compiler turns your code into tight machine instructions with nothing hidden in between.
That control has a price. Nothing stops a C program from reading memory it has already freed, writing past the end of an array, or letting two threads change the same value at once. Mistakes like these do not always crash; they corrupt data quietly, and some of them let an attacker take over the program. Large software companies have said publicly that bugs of exactly this kind make up a large share of their most serious security problems, year after year, despite skilled engineers and heavy testing.
Most other popular languages (Java, Python, Go, JavaScript, C#) avoid those bugs with a garbage collector: a part of the runtime that finds memory nobody uses any more and frees it. That works well for a huge range of programs, but it costs memory and CPU time, it can pause the program at moments you don't choose, and it makes the language harder to embed in places like an operating-system kernel or a microcontroller with a few kilobytes of RAM.
Rust takes a third road. It has no garbage collector, yet safe Rust code cannot use freed memory, cannot read past the end of an array without being stopped, and cannot share data between threads in a way that races. The trick is that the compiler enforces a small set of rules about who owns each value and who may borrow it, and refuses to build a program that breaks them. The checking happens once, when you compile, so the finished program pays nothing for it at run time.
That is the bargain at the heart of this course: you spend more effort convincing the compiler that your program is sound, and in exchange a whole category of bugs disappears. The rest of these lessons teach you how to make that bargain comfortably.
Where Rust came from
Rust began in 2006 as a personal project of Graydon Hoare, a programmer at Mozilla. Mozilla started sponsoring it in 2009 and announced it publicly in 2010, because it wanted a safer language for writing a web browser, one of the most security-sensitive programs most people run. The early language looked quite different from today's: it had a garbage collector, lightweight green threads and several kinds of pointers built into the syntax. Over the following years the community stripped those out, one by one, until what remained was the idea of ownership checked at compile time.
Rust 1.0 was released on 15 May 2015, with a promise that code written for 1.0 would keep compiling on later versions. Since then a new stable compiler has shipped every six weeks, like a train leaving on schedule: features that are ready get on, features that are not wait for the next one. Three release channels run side by side: nightly (built every day, with unfinished features behind flags), beta (the next stable, being tested) and stable (what almost everyone uses).
Mozilla's research browser engine, Servo, was the first large Rust program, and pieces of it (notably a parallel CSS engine) went into Firefox in 2017. In 2021 stewardship of the project's infrastructure passed to the independent Rust Foundation, supported by several large technology companies. Rust is now used in parts of Firefox, Android, Windows and the Linux kernel (which accepted Rust as a second language for drivers starting with version 6.1 in late 2022), in cloud infrastructure, in command-line tools you may already use, and in many small companies' web services.
To change the language without breaking old code, Rust uses editions: 2015, 2018, 2021 and 2024 (introduced with Rust 1.85 in February 2025). An edition is a setting in each project that can switch on a few incompatible changes, such as new keywords. Crates written in different editions link together without trouble, so the ecosystem never splits. This course uses the 2024 edition throughout.
The toolchain: rustup, rustc and Cargo
You install Rust with one program and then mostly talk to another. Here are the pieces.
Definition— rustup
rustup is the toolchain installer and manager. It downloads the compiler, the standard library, Cargo and optional components (the formatter rustfmt, the linter clippy, offline documentation), keeps them up to date with rustup update, and can hold several versions at once, for example stable alongside nightly.
Definition— rustc
rustc is the Rust compiler. It reads a source file (ending in .rs), checks it, and produces a native executable or a library. You rarely call it directly.
Definition— Cargo and crates
Cargo is Rust's build tool and package manager. A crate is the unit of compilation, either a binary (a program) or a library; a package is a directory with a Cargo.toml file describing one or more crates and their dependencies. Cargo creates projects, downloads dependencies from the public registry at crates.io, calls rustc with the right flags, runs tests and builds documentation.
On Linux and macOS the installer is a one-line shell command shown on rust-lang.org/tools/install; on Windows it is a small .exe, and you will also need Microsoft's C++ build tools for the linker (the installer explains). Afterwards, check what you have:
rustc --version
cargo --version
rustup update # later, to move to the newest stable releaseThe exact numbers will differ from machine to machine. Rust's version numbers climb by one every six weeks, so do not worry if yours is newer than the one used to check this course; the 1.0 compatibility promise means these programs will still compile.
If you would rather not install anything yet, the Rust Playground compiles and runs programs in your browser. Every complete program in this course runs there unchanged.
Your first programs
Hello, world, and a project to put it in
Create a project with Cargo:
cargo new hello
cd hello
cargo runcargo new makes a directory with two files. The manifest, Cargo.toml, names the package and its edition:
[package]
name = "hello"
version = "0.1.0"
edition = "2024"
[dependencies]and src/main.rs holds the program. Here is a slightly longer version of the one Cargo generates:
fn main() {
println!("Hello, world!");
println!("Habari, dunia! Olá, mundo! नमस्ते दुनिया!");
}Hello, world!
Habari, dunia! Olá, mundo! नमस्ते दुनिया!Read it line by line:
fn main()declares a function calledmain. Every executable starts there. It takes no arguments and returns nothing.- The body sits between braces, indented four spaces by convention.
println!prints a line. The!matters:println!is a macro, not a function. Macros run at compile time and expand into ordinary code; this one checks your format string against its arguments before the program ever runs.- Each statement ends with a semicolon.
- String literals in double quotes are UTF-8, so Swahili, Portuguese and Hindi all print as written.
When you type cargo run, Cargo compiles the project (in debug mode, quick to build and easy to debug, but not optimised), puts the executable in target/debug/, and runs it. Three other commands you will use constantly:
| Command | What it does |
|---|---|
cargo check | Type-checks the code without producing an executable. The fastest way to ask "does it compile?" |
cargo build | Compiles a debug executable into target/debug/ without running it. |
cargo build --release | Compiles with optimisations into target/release/. Slower to build, often many times faster to run. |
Professionals run cargo check dozens of times an hour (most editors do it for you on every save, through the rust-analyzer language server) and only build in release mode to measure speed or to ship.
Printing values
println! takes a format string followed by values. Each {} is a placeholder; you can also name a variable inside the braces, and add a colon followed by formatting instructions:
fn main() {
let language = "Rust";
let year = 2015;
let ratio = 2.0 / 3.0;
println!("{language} 1.0 was released in {year}.");
println!("{} + {} = {}", 2, 3, 2 + 3);
println!("two thirds is about {ratio:.3}");
println!("[{:>6}] [{:<6}] [{:^6}]", "right", "left", "mid");
println!("[{:05}]", 42);
println!("{:?}", ("tuple", 7, true));
println!("{{braces}} are written doubled");
}Rust 1.0 was released in 2015.
2 + 3 = 5
two thirds is about 0.667
[ right] [left ] [ mid ]
[00042]
("tuple", 7, true)
{braces} are written doubledA few things to notice:
letintroduces a variable. The compiler works out thatyearis an integer andratioa floating-point number; lesson 2 says exactly which types it picks.{ratio:.3}rounds to three decimal places,{:>6}right-aligns in a field six characters wide (<left,^centre), and{:05}pads a number with zeros.{}uses a type's Display formatting, meant for users.{:?}uses its Debug formatting, meant for programmers; many types (like this tuple) have Debug but no Display. You will use{:?}constantly while learning, and{:#?}prints the same thing spread over several lines.- To print a literal brace, double it.
Related macros follow the same rules: print! (no newline at the end), eprintln! (to standard error, where diagnostics belong), and format! (builds a String instead of printing).
A program that computes something
This one defines a function and loops over an array of pairs. Loops and functions have their own lessons; for now, read it for its shape:
fn fahrenheit(celsius: f64) -> f64 {
celsius * 9.0 / 5.0 + 32.0
}
fn main() {
let readings = [("Nairobi", 24.0), ("Oslo", -3.5), ("Lima", 19.0), ("Delhi", 41.0)];
for (city, c) in readings {
println!("{city:<8} {c:>5.1} °C = {:>5.1} °F", fahrenheit(c));
}
}Nairobi 24.0 °C = 75.2 °F
Oslo -3.5 °C = 25.7 °F
Lima 19.0 °C = 66.2 °F
Delhi 41.0 °C = 105.8 °FThe function signature fn fahrenheit(celsius: f64) -> f64 says: one parameter, a 64-bit float, and a 64-bit float comes back. Parameter and return types are always written out in Rust; inside function bodies the compiler infers most types for you. The body has no return and no semicolon on its last line: the value of the final expression is the return value. That small rule (blocks are expressions) turns out to run through the whole language.
How a Rust program runs, and how to read the compiler
Rust is compiled ahead of time to native machine code. There is no virtual machine and no interpreter: the file in target/release/ is a program your operating system runs directly, and you can copy it to another machine of the same kind and run it there without installing Rust. The standard library is linked into it. A small runtime does exist (it sets up the main thread and prints a message if the program panics), but there is no garbage collector running beside your code.
Two consequences follow. First, Rust programs start instantly and their speed is in the same league as C and C++. Second, compiling takes real work: the compiler checks types and ownership, then hands the program to LLVM, the same optimiser that powers Clang, to generate machine code. Large Rust projects are known for slow builds, and experienced teams manage that with cargo check, incremental compilation and splitting code into several crates.
The other half of working in Rust is reading the compiler's messages, which are unusually helpful. Suppose you misspell a variable:
fn main() {
let greeting = "Salaam";
println!("{greting}, Yusuf!");
}The compiler refuses, and says why:
error[E0425]: cannot find value `greting` in this scope
--> err.rs:3:16
|
3 | println!("{greting}, Yusuf!");
| ^^^^^^^ help: a local variable with a similar name exists: `greeting`
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0425`.Every part is useful. E0425 is an error code; rustc --explain E0425 (or the online error index) prints a long explanation with examples. The arrow gives the file, line and column. The carets underline the exact span, and the help: line proposes a fix. Notice too that the mistake inside the format string was caught at compile time: that is the println! macro at work.
Note
Get into the habit of reading the first error first. Later errors are often consequences of the first one, and fixing it makes them vanish. When you meet the ownership errors of lesson 4, the compiler will often point at two places at once ("value moved here", "value used here after move"); read both.
Common misconceptions
Misconception
"Rust is only for operating systems and other low-level code." Rust is a systems language, but many people use it for web back ends, command-line tools, data pipelines and WebAssembly in the browser, because the same guarantees (no data races, no null pointers, predictable performance) help there too. It is a poor fit where you want to explore quickly and throw code away, or where a garbage collector costs you nothing; that is an honest trade-off, not a failing.
Misconception
"cargo build makes the fast version." It makes a debug build, which can be ten or more times slower than a release build for numeric code. Benchmark and ship with cargo build --release (or cargo run --release).
Misconception
"println! is just a function with a funny name." The exclamation mark marks a macro. That is why println! can take any number of arguments of different types and why a typo in {greting} is a compile error rather than a surprise at run time.
Misconception
"I will be fighting the compiler forever." Nearly everyone finds the first weeks of Rust frustrating, because the compiler rejects programs that look fine. That phase passes as you learn the handful of ownership rules and start designing data so they hold naturally. Many experienced Rust programmers say the compiler becomes a collaborator: once a program compiles, a lot of things that could go wrong in other languages already cannot.
Exercises
Use the Playground or your own cargo new project to try anything you are unsure of.
1. Getting started with Rust
Warm-upHumanYou want to switch your machine from one stable Rust release to the next one that just came out. Which tool do you use?
2. Getting started with Rust
Warm-upHumanWhat does cargo check do?
3. Getting started with Rust
CoreComputationalWhat does this program print? Write the three lines separated by single spaces.
fn main() {
let n = 7;
println!("{n}:{}", n * n);
println!("{}{}", 4, 2 * 5);
println!("{:.1}", 10.0 / 4.0);
}
4. Getting started with Rust
CoreComputationalHow many lines does this program print?
fn main() {
println!("a");
print!("b");
print!("c");
println!();
println!("{}", "d\ne");
}
5. Getting started with Rust
CoreHumanWhy can the compiler reject println!("{greting}") when greting is misspelled, before the program runs?
6. Getting started with Rust
StretchHumanWhich statements about Rust editions are true? Choose all that apply.
Further reading and resources
- Install RustThe official installer, rustup, for Linux, macOS and Windows.
- The Rust Programming Language, chapter 1: Getting Started · Steve Klabnik, Carol Nichols, Chris Krycho and the Rust community
- The Cargo BookEverything Cargo can do, from cargo new to publishing a crate.
- The std::fmt moduleThe full format-string language used by println!, format! and friends.
- The Rust Edition GuideWhat each edition (2015, 2018, 2021, 2024) changed and how to migrate.
- Rust PlaygroundRun any program from this lesson in your browser.