Skip to main content

IndexRustTutorial

Rust Setup on Windows, macOS and Linux for Web Devs

Part 1 of Rust for web developers. Install Rust on any OS, set up VS Code with rust-analyzer, learn Cargo, and map Rust to JavaScript, Python and Go.

By LearnWebCraft Team39 min readBeginner

Part 1 of 15 · Rust for web developers

If you build for the web, you have probably bumped into Rust without writing any of it. The tools you already use are full of it. The Tailwind v4 engine, Turbopack in Next.js, the SWC compiler that turns your TypeScript into JavaScript, Biome, Rolldown in Vite, Deno's runtime, half of what Cloudflare runs at the edge. At some point it is reasonable to wonder what the language looks like from the inside, and whether you could write a web backend in it yourself.

This series answers that with code. Over fifteen parts we go from a machine with nothing installed to a real web API written with Axum, backed by PostgreSQL, tested, packed into a small Docker image and deployed. The first nine parts are about Rust itself, because trying to learn a web framework and a new language with a strict compiler at the same time is how people burn out in week two. The last six are the web part.

This first part is the boring one that everyone skips and then regrets skipping. We install Rust properly on Windows, macOS and Linux, set up an editor that actually helps, learn the handful of Cargo commands you will type every day, and build a small but complete command line program. Along the way I'll keep translating Rust ideas into things you already know from JavaScript, TypeScript, Python, Go, C# or Java.

A note on how this was written. Every Linux command and every piece of terminal output in this article was copied from a real run inside the official rust:latest Docker image, which ships Rust 1.100.0 at the time of writing. I can't capture Windows and macOS installer screens the same way, so those sections follow the official rustup and Microsoft documentation and describe what you should see rather than pasting output I didn't produce.

What you will have at the end of this part

By the end you will have:

  1. Rust installed through rustup, the official toolchain manager, on whatever OS you use.
  2. VS Code (or RustRover, or Zed) set up with real-time type information, inline errors and format on save.
  3. A working understanding of cargo new, cargo run, cargo check, cargo build --release, cargo test, cargo add, cargo fmt and cargo clippy.
  4. A word frequency counter that reads a file, handles missing files and bad input without crashing, uses a third-party crate, and has two passing unit tests.
  5. A mental map of how Rust's ideas line up with the language you already know.

It takes about an hour if you type along, a bit longer on Windows because of the C++ build tools download.

Why web developers are learning Rust at all

It is worth being honest about this before you invest the time.

Rust is a compiled, statically typed language with no garbage collector. Memory is freed when the value that owns it goes out of scope, and the compiler proves at build time that you never use memory after it has been freed, never share mutable data across threads without protection, and never read a null pointer. That last sentence is the whole pitch. You get the speed and small memory footprint of C or C++, without the class of bugs that make C and C++ code a security problem.

For web work that turns into a few practical things.

Rust web servers are fast and use very little memory. There is no runtime or garbage collector sitting in memory next to your code, so a small API needs a fraction of the RAM. When I measured a minimal JSON endpoint for the framework comparison post linked at the end, every Rust server idled at about 1 MB of memory, while a plain Node.js server doing the same job idled at about 10.6 MB. On a cheap VPS or a serverless platform that bills by memory, that is real money.

A Rust program compiles to a single binary with no runtime to install. You can copy it to a server and run it. Docker images built from Rust programs are often under 20 MB.

The type system catches mistakes that would be runtime errors in JavaScript. If a function can fail, its return type says so and you cannot forget to handle it. If a value might be missing, its type says that too. There is no undefined is not a function at 3 a.m.

Rust also runs in the browser through WebAssembly, and on edge platforms like Cloudflare Workers. One language can cover the server, the edge and heavy client-side work.

The cost is the learning curve. Rust is harder to learn than Go or Python, and the compiler will reject code that you are sure is fine. Most of that friction comes from one idea, ownership, which gets its own part later in this series. My advice is to expect the first two weeks to feel slow, and to read compiler errors slowly and completely. They are some of the best error messages of any language, and they usually tell you the fix.

If you mostly build marketing sites or content apps in Next.js, you do not need Rust. If you build APIs, background workers, data pipelines, CLI tools or anything where performance and correctness matter, it is worth learning.

How Rust maps to what you already know

Before installing anything, here is the map. You don't need to memorise this. Come back to it when something in a later part feels foreign.

Tooling

What you know Rust equivalent Notes
Node.js, Python interpreter rustc (the compiler) You rarely call it directly
nvm, pyenv, asdf rustup Installs and switches Rust versions
npm, pnpm, pip, go mod cargo Builds, runs, tests, manages dependencies
package.json, pyproject.toml, go.mod Cargo.toml Project manifest
package-lock.json, go.sum Cargo.lock Exact resolved versions
npm registry, PyPI crates.io Packages are called crates
node_modules ~/.cargo/registry plus target/ Dependencies are cached globally, build output goes in target/
Prettier, gofmt, Black rustfmt via cargo fmt One official style, no config arguments
ESLint, pylint, go vet Clippy via cargo clippy Hundreds of lints, many with automatic fixes
Jest, Vitest, pytest built in, cargo test No test framework to install
TypeScript language server rust-analyzer Powers editor features
MDN, npm docs docs.rs, rustup doc Every crate gets generated docs on docs.rs

The one that surprises people most is that testing, formatting, linting, documentation generation and benchmarking all come with the toolchain. There is no "which test runner should we use" debate in Rust. There is one.

Language ideas

Idea JavaScript / TypeScript Python Go Rust
Typing Dynamic, optional static (TS) Dynamic, optional hints Static Static, strongly inferred
Variables let, const name = value var, := let (immutable by default), let mut
Missing value null, undefined None nil Option<T>: Some(value) or None
Errors throw, try/catch raise, try/except return value, err Result<T, E>: Ok(value) or Err(error)
Memory Garbage collected Garbage collected Garbage collected Ownership, freed at end of scope
Objects classes, object literals classes structs structs plus impl blocks
Interfaces TS interface protocols, ABCs interfaces traits
Generics Array<T> list[T] [T any] Vec<T>
Async async/await, built-in event loop asyncio goroutines async/await, runtime chosen by you (usually Tokio)
Pattern matching switch, destructuring match (3.10+) switch match, exhaustive, checked by the compiler
Inheritance yes yes no no, composition and traits instead

A few things in that table deserve a sentence each, because they shape everything that comes later.

Variables are immutable unless you write mut. In JavaScript terms, every let behaves like const until you opt out. This feels annoying for about a day and then you start to appreciate seeing at a glance which values can change.

There is no null. A value that might be missing has the type Option<T>, and the compiler will not let you use it as a T until you have checked which case you have. TypeScript's strict null checks are a gentle version of the same idea. Rust's is not optional.

There are no exceptions. A function that can fail returns Result<T, E>. You handle it with match, or pass it up to the caller with the ? operator. If you have written Go, this is like if err != nil, but the compiler forces you to deal with it and the ? operator removes most of the noise.

There is no garbage collector, and there is also no manual free. The compiler tracks who owns each value. This is the ownership system, and it is the reason Rust feels different. We will spend all of part 3 on it.

Async needs a runtime. JavaScript has an event loop built into the engine. Rust's async keyword only builds a state machine, and you pick a runtime to drive it. In practice almost the whole web ecosystem uses Tokio, so this is less of a choice than it sounds.

If you are coming from a specific language

From JavaScript or TypeScript, the biggest shift is that the compiler is the gatekeeper. In JS you find mistakes by running code. In Rust you find them by compiling it, and a program that compiles usually works. Expect to spend more time before the first run and much less time debugging afterwards.

From Python, the syntax will feel noisier at first: braces, semicolons, type annotations on function signatures. The payoff is speed. Rust code is commonly tens of times faster than the same logic in pure Python.

From Go, you will find Rust more expressive and more demanding. Go optimises for being easy to read and quick to learn. Rust optimises for catching mistakes and zero-cost abstractions. Error handling will feel familiar, generics will feel more powerful, and ownership will be new.

From C# or Java, traits are close to interfaces, impl blocks are close to methods on a class, and enums are far more powerful than you are used to, because each variant can carry its own data. There is no inheritance, and you won't miss it as much as you think.

Installing Rust

The right way to install Rust on every OS is rustup. It installs the compiler, Cargo and the standard library, puts them on your PATH, and lets you update with one command. Rust ships a new stable release every six weeks, so you want updates to be easy.

Avoid installing Rust from your Linux distribution's package manager or from Homebrew's rust formula. Those give you a fixed compiler version that often lags months behind, and many crates set a minimum Rust version that the packaged compiler won't meet. You will also not get rustup, which the rest of this series assumes you have.

Windows

Rust on Windows has one prerequisite that trips up most people: a C++ linker. Rust compiles your code, but it uses Microsoft's linker and the Windows SDK libraries to produce the final .exe. These come from Visual Studio or the standalone Visual Studio Build Tools. Without them, everything appears to install fine and then your first cargo run fails with an error that link.exe was not found.

The good news is that the rustup installer now handles this for you in most cases.

Go to rustup.rs and download rustup-init.exe. Most machines want the 64-bit x86_64 version. If you are on an ARM laptop such as a Snapdragon-based Surface, take the ARM64 build.

Run it. If it can't find Visual Studio, it will tell you that the MSVC prerequisites are missing and offer to install them by downloading the Visual Studio Community installer. Accept that. It selects the right workload for you. The download is a few gigabytes, so this is the slow part.

If you prefer to install the prerequisites yourself, or the automatic option fails, install Visual Studio 2022 Community or the Visual Studio Build Tools, and in the installer select the workload called "Desktop development with C++". At minimum you need the MSVC v143 C++ x64/x86 build tools and a Windows 11 SDK (the Windows 10 SDK works on Windows 10). Then run rustup-init.exe again.

One licensing note. Microsoft says the Build Tools require a valid Visual Studio license. Visual Studio Community is free for individuals, open source work, education and small teams, which covers most people reading this. If you are at a larger company, check with whoever manages software licenses.

Back in the rustup installer, you will be asked how to proceed. Choose the default installation by pressing Enter. It installs the stable toolchain for the x86_64-pc-windows-msvc target, along with the default profile: the compiler, Cargo, the standard library, rustfmt, Clippy and the offline documentation.

If you already use winget, this one line installs rustup itself, and you then still need the C++ build tools as described above:

Fig. 1powershell
winget install --id Rustlang.Rustup -e

When the installer finishes, close every terminal window and open a new one. The installer adds %USERPROFILE%\.cargo\bin to your user PATH, but terminals that were already open will not see the change. This step catches a lot of people. For VS Code's integrated terminal, restart VS Code itself. A new terminal tab is not enough.

A word on the GNU toolchain and WSL

You will find guides that suggest the x86_64-pc-windows-gnu toolchain to avoid installing Visual Studio. It works, but it uses a different ABI from almost everything else on Windows, some crates that link to native libraries don't support it well, and debugging is harder. Use MSVC unless you have a specific reason not to.

WSL is a different story, and a good one. If you already do your web development inside WSL 2 with Ubuntu, install Rust inside WSL using the Linux instructions below and ignore the Windows installer entirely. Your Rust programs will be Linux programs, which matches what you will deploy to a server anyway. Keep your project files inside the Linux filesystem (~/projects, not /mnt/c/...), because compiling across the Windows filesystem boundary is several times slower.

Windows Defender and slow builds

Rust builds create and read thousands of small files in the target folder. Real-time antivirus scanning each of those can make builds noticeably slower. If builds feel sluggish, Windows 11 Dev Drive is the cleanest fix: put your projects on a Dev Drive, which uses performance mode for Defender. Excluding your projects folder and %USERPROFILE%\.cargo from real-time scanning also works. Only do that for folders you control.

macOS

macOS needs Apple's command line developer tools, which provide the linker and system headers. Open Terminal and run:

Fig. 2bash
xcode-select --install

A dialog will pop up asking to install the tools. You do not need the full Xcode app from the App Store, which is many gigabytes. If the command says the tools are already installed, you are fine.

Then install rustup with the official script:

Fig. 3bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

The --proto '=https' --tlsv1.2 part makes curl refuse anything but a modern HTTPS connection, which is why you'll see it in the official docs. Piping a script into sh is a habit worth questioning in general. Here the script comes from the Rust project's own domain over HTTPS, and you can open the URL in a browser first if you want to read it.

The installer asks how to proceed. Press Enter for the default. When it finishes, it tells you to either open a new terminal or run:

Fig. 4bash
. "$HOME/.cargo/env"

That loads Cargo's bin folder onto your PATH for the current session. New terminals will pick it up automatically from your shell profile.

Apple Silicon and Intel Macs both work the same way. rustup detects your architecture and installs aarch64-apple-darwin or x86_64-apple-darwin as appropriate.

If you use Homebrew, there is a rustup formula (brew install rustup), which is fine. Don't confuse it with the rust formula, which installs a standalone compiler without rustup. If you have the rust formula installed from some time ago, remove it with brew uninstall rust before installing rustup, otherwise you will have two compilers fighting over your PATH.

Linux

Linux needs a C compiler and linker. Most desktop installs already have them. If not, install your distribution's build essentials first.

On Ubuntu, Debian, Pop!_OS and Mint:

Fig. 5bash
sudo apt update
sudo apt install build-essential curl

On Fedora:

Fig. 6bash
sudo dnf install gcc curl

On Arch and Manjaro:

Fig. 7bash
sudo pacman -S base-devel curl

Later in the series, when we connect to PostgreSQL over TLS, some crates need OpenSSL development headers as well (libssl-dev and pkg-config on Debian and Ubuntu, openssl-devel on Fedora). You can install them now or wait until a build complains. We will mostly use pure-Rust TLS to avoid the problem.

Then run the same script as macOS:

Fig. 8bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
. "$HOME/.cargo/env"

Checking the install

On any OS, open a fresh terminal and run:

Fig. 9bash
rustc --version
cargo --version
rustup --version

This is what the official Docker image printed when I ran it for this article:

Fig. 10text
rustc 1.100.0 (0ef1bc386 2026-11-09)
cargo 1.100.0 (3acc79c0c 2026-11-05)
rustup 1.29.3 (edbc831ce 2026-11-02)

Your numbers will be the same or newer. Yes, the version really is 1.100. Rust has been on 1.x since 2015 and keeps counting, because the project promises not to break stable code. Code written for Rust 1.0 still compiles today.

rustup show tells you what is installed and which toolchain is active:

Fig. 11text
Default host: x86_64-unknown-linux-gnu
rustup home:  /usr/local/rustup

installed toolchains
--------------------
1.100.0-x86_64-unknown-linux-gnu (active, default)

active toolchain
----------------
name: 1.100.0-x86_64-unknown-linux-gnu
active because: it's the default toolchain
installed targets:
  x86_64-unknown-linux-gnu

On your machine, the toolchain will probably be called stable-x86_64-pc-windows-msvc, stable-aarch64-apple-darwin or stable-x86_64-unknown-linux-gnu. The rustup home will be inside your user folder (~/.rustup or %USERPROFILE%\.rustup).

Finally, check that Clippy and rustfmt came with the install:

Fig. 12bash
rustup component list --installed

You should see clippy, rustfmt, rust-docs and a few others in the list. If they are missing, add them:

Fig. 13bash
rustup component add clippy rustfmt

This happened to me inside the Docker image, which uses rustup's minimal profile to keep the image small. A normal desktop install uses the default profile and includes both.

Keeping Rust up to date

Every six weeks, run:

Fig. 14bash
rustup update

That is the whole update process. It updates every installed toolchain and its components.

Toolchains, briefly

rustup can install several toolchains side by side. stable is what you want almost all the time. beta is the next release, and nightly is built every day and has unstable features. Some tools need nightly, but nothing in this series does.

If a project needs a specific version, you can pin it by putting a file called rust-toolchain.toml in the project root:

Fig. 15toml
[toolchain]
channel = "1.100.0"
components = ["clippy", "rustfmt"]

rustup reads that file automatically when you run cargo inside the folder and installs the version if it is missing. This works like .nvmrc for Node, except you don't have to remember to run anything.

Offline docs

rustup doc opens the standard library documentation and the Rust book in your browser, served from your disk. rustup doc --std goes straight to the standard library reference. It is useful on trains and planes.

Picking an editor

Rust without editor support is painful, because so much information lives in types you don't write down. Rust infers most types, which keeps code short, but you want to see them while you learn. Every good Rust editor setup is built on rust-analyzer, the official language server. It provides completions, inline type hints, go to definition, rename, inline errors and quick fixes.

VS Code with rust-analyzer (my recommendation)

If you already use VS Code for web work, stay there. Install one extension: rust-analyzer, published by The Rust Programming Language (its ID is rust-lang.rust-analyzer).

Do not install the old extension simply called "Rust" by rust-lang. It is deprecated and conflicts with rust-analyzer. If you have it from years ago, uninstall it.

The extension uses the rust-analyzer server that ships with it, so you don't need to install anything else. Open a Rust project folder (the folder containing Cargo.toml, not a parent of it) and it starts indexing. The first time takes a few seconds while it analyses the standard library. You'll see a spinner in the status bar.

These are the settings I change. Open your settings JSON with the command palette (Preferences: Open User Settings (JSON)) and add:

Fig. 16json
{
  "rust-analyzer.check.command": "clippy",
  "[rust]": {
    "editor.defaultFormatter": "rust-lang.rust-analyzer",
    "editor.formatOnSave": true
  },
  "rust-analyzer.inlayHints.typeHints.enable": true,
  "rust-analyzer.inlayHints.parameterHints.enable": true
}

check.command: "clippy" makes rust-analyzer run Clippy instead of plain cargo check every time you save, so lint warnings show up in the editor instead of only when you remember to run them. It is a little slower on big projects, and on a learning project you won't notice.

Format on save with rust-analyzer as the formatter runs rustfmt for you. The JSON block scopes it to Rust files so it doesn't fight Prettier in your web projects.

Inlay hints show the inferred type of each variable in grey next to it. While you are learning, leave these on. They are the single most useful learning aid in the Rust toolchain. Later you might turn parameter hints off if they get noisy.

For debugging, install CodeLLDB (vadimcn.vscode-lldb). It lets you set breakpoints in Rust code, and rust-analyzer adds "Debug" buttons above main and above each test. On Windows with the MSVC toolchain you can also use Microsoft's C/C++ extension debugger, but CodeLLDB works on every OS and is what I use.

Two more extensions are worth having. Even Better TOML gives you syntax highlighting and validation for Cargo.toml. Error Lens shows errors inline at the end of the line instead of only as squiggles, which helps a lot when the compiler has a lot to say.

RustRover

RustRover is JetBrains' dedicated Rust IDE. If you already use WebStorm or IntelliJ, it will feel familiar. It has its own analysis engine instead of rust-analyzer, excellent refactoring, a built-in debugger and database tools, and it works without configuration.

JetBrains offers it free for non-commercial use, which covers learning, hobby projects, open source and content creation. If you are paid for the work you do in it, you need a commercial license. The free license requires a JetBrains account, renews yearly as long as you used it in the last six months, and you can't opt out of anonymous usage statistics. Read the current terms on JetBrains' site before relying on it at work.

Zed

Zed is a fast editor written in Rust, by some of the people who built Atom. It has built-in Rust support through rust-analyzer, so you install it and open a folder. It is a good choice if VS Code feels slow on your machine. Its extension ecosystem is smaller than VS Code's.

Neovim and Helix

If you live in a terminal editor, both work well. Helix supports rust-analyzer out of the box. Neovim needs the language server set up through its built-in LSP client and a plugin like rustaceanvim. I won't cover the configuration here, because if you use Neovim you already know how this goes.

Your first project

Pick a folder for your Rust projects and run:

Fig. 17bash
cargo new hello-rust
cd hello-rust

Cargo prints:

Fig. 18text
    Creating binary (application) `hello-rust` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

"Binary" means a program you can run, as opposed to a library. You'd use cargo new --lib for a library.

Here is what Cargo created:

Fig. 19text
.
./.gitignore
./Cargo.toml
./src
./src/main.rs

It also ran git init for you, and the .gitignore already ignores the target folder. If you don't want a git repository, pass --vcs none.

Cargo.toml is the manifest:

Fig. 20toml
[package]
name = "hello-rust"
version = "0.1.0"
edition = "2024"

[dependencies]

edition deserves an explanation because it confuses people. An edition is a set of language rules, not a compiler version. Rust has had editions 2015, 2018, 2021 and 2024. New editions can change small things, such as adding new keywords. Each crate declares its own edition, and crates of different editions work together in the same build. This is how Rust adds features without breaking old code. New projects default to the latest edition, 2024, and you don't need to think about it again.

src/main.rs is the entry point:

Fig. 21rust
fn main() {
    println!("Hello, world!");
}

fn declares a function. main is where the program starts, the same as in C, Go or Java. println! prints a line. The ! means it is a macro, not a function. Macros generate code at compile time. You don't need to write macros for a long time, but you use them constantly: println!, format!, vec! and assert_eq! all have the !. The reason println! is a macro is that it checks your format string against the arguments at compile time. If you write println!("{} {}", x) with one argument for two placeholders, it is a compile error, not a runtime surprise.

Run it:

Fig. 22bash
cargo run
Fig. 23text
   Compiling hello-rust v0.1.0 (/work/hello-rust)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.41s
     Running `target/debug/hello-rust`
Hello, world!

cargo run compiled the program, then ran the result. Run it a second time without changing anything and it skips the compile, because nothing changed.

The Cargo commands you'll actually use

There are only a handful.

cargo check

Fig. 24bash
cargo check
Fig. 25text
    Checking hello-rust v0.1.0 (/work/hello-rust)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.37s

cargo check runs the compiler's analysis, including type checking and the borrow checker, but stops before generating machine code. It is much faster than a full build. When you are working through compiler errors, use check in a loop. This is also what rust-analyzer runs behind the scenes when you save a file.

cargo build and the release profile

Fig. 26bash
cargo build            # debug build
cargo build --release  # optimised build

Debug builds compile quickly and include debug information, but the code is not optimised. Release builds take longer to compile and produce much faster code. I compared the two binaries for this tiny program:

Fig. 27text
-rwxr-xr-x 2 root root 4501056 Nov 30 06:51 target/debug/hello-rust
-rwxr-xr-x 2 root root  445032 Nov 30 06:51 target/release/hello-rust

The debug binary is about 4.5 MB and the release binary about 445 KB, for a program that prints one line. The difference is mostly debug symbols. For a real web server the speed difference between debug and release can be ten times or more, so always benchmark and deploy release builds. Debug builds are only for development.

Build output lives in target/debug/ and target/release/. You can run the binary directly from there, and on Windows it is target\release\hello-rust.exe. The target folder can get big, several gigabytes on large projects, because it caches compiled dependencies. cargo clean deletes it whenever you want the space back.

Cargo.lock

After your first build there is a Cargo.lock file. It records the exact version of every dependency. Commit it to git for applications. The old advice was to leave it out for libraries, but the Cargo team changed that guidance in 2023, and committing it is now fine for both.

Reading your first compiler error

The compiler is going to be your main teacher in this series, so let's look at an error on purpose. Replace src/main.rs with this:

Fig. 28rust
fn main() {
    let language = "JavaScript";
    println!("I write {language}");
    language = "Rust";
    println!("Now I write {language}");
}

In JavaScript, with let, this would be fine. Run it:

Fig. 29text
   Compiling hello-rust v0.1.0 (/work/hello-rust)
error[E0384]: cannot assign twice to immutable variable `language`
 --> src/main.rs:4:5
  |
2 |     let language = "JavaScript";
  |         -------- first assignment to `language`
3 |     println!("I write {language}");
4 |     language = "Rust";
  |     ^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
2 |     let mut language = "JavaScript";
  |         +++

For more information about this error, try `rustc --explain E0384`.
error: could not compile `hello-rust` (bin "hello-rust") due to 1 previous error

Read it top to bottom, every time. That habit is the most useful thing I can teach you in this part.

The first line gives an error code, E0384, and a one-sentence summary. The arrow line gives the file, line and column. Then the compiler draws your code with annotations: where the first assignment happened, and where the second one broke the rule. Then comes a help section with the exact fix, shown as a diff with +++ under the characters to add. Finally, it tells you how to read a longer explanation.

Try that last suggestion:

Fig. 30bash
rustc --explain E0384

It prints a page explaining the error with examples. Every error code has one.

Apply the fix, adding mut, and the program compiles. In rust-analyzer, you can also put your cursor on the red squiggle and press Ctrl+. (or Cmd+. on macOS) to apply the suggested fix automatically.

Notice also println!("I write {language}"). Variables can go directly inside the braces of a format string, like template literals in JavaScript. For more complex expressions you use empty braces and pass arguments: println!("{} words", count + 1).

A real program: a word frequency counter

Hello world doesn't teach much. Let's build something small that does real work: a command line tool that reads a text file and prints the most common words. It touches command line arguments, file IO, error handling, a hash map, sorting, closures, a third-party crate and tests. You won't understand every line yet, and that's fine. Each of these ideas gets a full part later. The goal today is to see what a whole Rust program looks like and get comfortable with the edit, compile, run loop.

Fig. 31bash
cargo new wordfreq
cd wordfreq

Create a file called notes.txt in the wordfreq folder (next to Cargo.toml, not inside src):

Fig. 32text
Rust is fast. Rust is safe.
The compiler is strict, and the compiler is helpful.
Cargo builds the code, Cargo runs the tests, and Cargo fetches crates.

Now replace src/main.rs:

Fig. 33rust
use std::collections::HashMap;
use std::env;
use std::fs;
use std::process;

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() < 2 {
        eprintln!("usage: wordfreq <file>");
        process::exit(1);
    }

    let path = &args[1];

    let text = match fs::read_to_string(path) {
        Ok(contents) => contents,
        Err(error) => {
            eprintln!("could not read {path}: {error}");
            process::exit(1);
        }
    };

    let counts = count_words(&text);

    if counts.is_empty() {
        println!("{path} has no words in it");
        return;
    }

    let mut sorted: Vec<(&String, &usize)> = counts.iter().collect();
    sorted.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));

    println!(
        "{} words, {} unique",
        text.split_whitespace().count(),
        counts.len()
    );
    for (word, count) in sorted.iter().take(5) {
        println!("{count:>3}  {word}");
    }
}

fn count_words(text: &str) -> HashMap<String, usize> {
    let mut counts = HashMap::new();

    for raw in text.split_whitespace() {
        let word: String = raw
            .trim_matches(|c: char| !c.is_alphanumeric())
            .to_lowercase();

        if word.is_empty() {
            continue;
        }

        *counts.entry(word).or_insert(0) += 1;
    }

    counts
}

Run it. Everything after -- is passed to your program instead of to Cargo:

Fig. 34bash
cargo run -- notes.txt
Fig. 35text
   Compiling wordfreq v0.1.0 (/work/wordfreq)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 3.29s
     Running `target/debug/wordfreq notes.txt`
27 words, 16 unique
  4  is
  4  the
  3  cargo
  2  and
  2  compiler

Walking through it

use lines are imports. std is the standard library, which comes with every Rust install. use std::collections::HashMap; is like import { HashMap } from "std/collections" would be if JavaScript worked that way.

env::args() returns an iterator over the command line arguments, and .collect() gathers them into a vector. A Vec<String> is a growable list of strings, like a JavaScript array where every item must be a string. The type annotation is needed here because collect can build many kinds of collections, and Rust needs to know which one you want. This is one of the few places you'll regularly write a type on a let.

The first argument, args[0], is the program's own path, the same as process.argv in Node, so the file name is at index 1. If it's missing, eprintln! prints to standard error, and process::exit(1) quits with a failure code.

let path = &args[1]; borrows the string instead of copying it. The & means "a reference to". This is your first glimpse of ownership. args owns the strings, and path is allowed to look at one of them. Part 3 is all about this.

fs::read_to_string(path) returns a Result<String, std::io::Error>. It's either Ok holding the file contents, or Err holding what went wrong. There's no exception to catch. The match handles both cases, and the compiler would refuse to build if you forgot one. That's the try/catch replacement in its plainest form. In part 5 we'll make this much shorter with the ? operator.

count_words(&text) passes a reference to the text into our function. Its signature, fn count_words(text: &str) -> HashMap<String, usize>, says it takes a string slice (a view into some string data) and returns a map from owned strings to unsigned integers. usize is the unsigned integer type Rust uses for sizes and counts.

Inside, split_whitespace() iterates over words. trim_matches strips anything that isn't a letter or number from both ends, so "fast." becomes "fast". The |c: char| !c.is_alphanumeric() part is a closure, Rust's arrow function. In JavaScript it would be (c) => !isAlphanumeric(c).

*counts.entry(word).or_insert(0) += 1; is the idiomatic way to count things in a map. entry finds the slot for a key, or_insert(0) creates it with zero if it doesn't exist, and returns a mutable reference to the count. The * dereferences that reference so += 1 changes the number in the map. In JavaScript you'd write counts[word] = (counts[word] ?? 0) + 1.

The last line of count_words is just counts with no semicolon and no return. In Rust, the last expression in a block is its value. You only write return to leave early. This feels odd for a week and then reads naturally.

Back in main, we turn the map into a vector of (word, count) pairs and sort it. The sort closure compares counts in descending order (b against a) and breaks ties alphabetically, which is why is comes before the. Without the tie breaker, the order of words with equal counts would change between runs, because HashMap iteration order is randomised in Rust on purpose. That's a security feature against a class of denial of service attacks, and a common source of flaky tests for newcomers.

{count:>3} right-aligns the number in three characters. Rust's format syntax is close to Python's f-strings.

Bad input does not crash it

Try the failure paths:

Fig. 36bash
cargo run -q -- nope.txt
Fig. 37text
could not read nope.txt: No such file or directory (os error 2)
Fig. 38bash
cargo run -q
Fig. 39text
usage: wordfreq <file>

Both exit with status 1, which is what scripts and CI pipelines expect from a failed command. The -q flag hides Cargo's own "Compiling" and "Running" lines.

An empty file is handled too:

Fig. 40text
empty.txt has no words in it

You'll notice the program has no null checks and no try/catch, yet every way it can fail is handled. That isn't because I was careful. It's because read_to_string returns a Result and the compiler would not let me ignore it. This is the experience Rust is built around.

Adding a crate

Crates are Rust packages. Let's add one to make the top word stand out with bold text in the terminal. The colored crate does that.

Fig. 41bash
cargo add colored
Fig. 42text
    Updating crates.io index
      Adding colored v3.1.1 to dependencies
             Features:
             - no-color
    Updating crates.io index
     Locking 3 packages to highest Rust 1.100.0 compatible versions
      Adding colored v3.1.1
      Adding windows-link v0.2.1
      Adding windows-sys v0.61.2

cargo add is the equivalent of npm install some-package. It added a line to Cargo.toml:

Fig. 43toml
[dependencies]
colored = "3.1.1"

The version "3.1.1" is a caret requirement, the same as ^3.1.1 in npm: any 3.x version from 3.1.1 up is allowed. Cargo.lock records the exact one used.

The output also lists features. Crates can have optional features you turn on with cargo add colored --features no-color, similar to optional peer packages in npm but resolved at compile time. Notice that it pulled in windows-sys too. That's a platform-specific dependency for colour support in the Windows console. On Linux and macOS it is recorded in the lockfile but never compiled.

Now use it. Add this import at the top of src/main.rs:

Fig. 44rust
use colored::Colorize;

And change the line that prints each word:

Fig. 45rust
println!("{count:>3}  {}", word.bold());

Colorize is a trait, which adds methods like .bold(), .red() and .green() to strings. Traits are like interfaces that can also add methods to existing types, a bit like extending a prototype in JavaScript, except it's scoped to wherever you import the trait and can't collide with other code. Part 7 covers traits.

Run it again and the words print in bold. The first build after adding a crate downloads and compiles it, which takes a moment. After that it is cached.

You can find crates on crates.io and their docs on docs.rs. Two signals I use to judge a crate are its recent download count and when it was last released. lib.rs is an alternative index that is easier to browse by category.

Formatting and linting

cargo fmt

Rust has one official code style, and cargo fmt applies it. To show what it does, I made the code a little messy with let path = &args[1]; and ran the check mode, which reports problems without changing files:

Fig. 46bash
cargo fmt --check
Fig. 47text
Diff in /work/wordfreq/src/main.rs:12:
         process::exit(1);
     }

-    let path    =   &args[1];
+    let path = &args[1];

     let text = match fs::read_to_string(path) {
         Ok(contents) => contents,
Diff in /work/wordfreq/src/main.rs:32:
     let mut sorted: Vec<(&String, &usize)> = counts.iter().collect();
     sorted.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));

-    println!("{} words, {} unique", text.split_whitespace().count(), counts.len());
+    println!(
+        "{} words, {} unique",
+        text.split_whitespace().count(),
+        counts.len()
+    );
     for (word, count) in sorted.iter().take(5) {
         println!("{count:>3}  {}", word.bold());

It exits with status 1 when files need formatting, which makes cargo fmt --check a good CI step. Run cargo fmt without --check to fix everything. If you set up format on save earlier, you'll never need to run it by hand.

The second diff is interesting. I had written the println! on one line and rustfmt split it, because the line was over its 100 character limit. Like Prettier, there's very little to configure, and that's on purpose. Every Rust project you open will look the same.

cargo clippy

Clippy is the linter. It knows hundreds of patterns that compile fine but could be clearer, faster or more correct. My first version of the program used if counts.len() == 0, which is exactly what you'd write in JavaScript. Clippy had an opinion:

Fig. 48bash
cargo clippy
Fig. 49text
warning: length comparison to zero
  --> src/main.rs:27:8
   |
27 |     if counts.len() == 0 {
   |        ^^^^^^^^^^^^^^^^^ help: using `is_empty` is clearer and more explicit: `counts.is_empty()`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#len_zero
   = note: `#[warn(clippy::len_zero)]` on by default

warning: `wordfreq` (bin "wordfreq") generated 1 warning (run `cargo clippy --fix --bin "wordfreq" -p wordfreq -- ` to apply 1 suggestion)

Clippy says what's wrong, what to write instead, links to the lint's documentation, and offers cargo clippy --fix to apply the change automatically. After switching to counts.is_empty(), Clippy is quiet.

I'd treat Clippy as a teacher as much as a lint step. Its suggestions are idiomatic Rust, and reading them teaches you how experienced Rust developers write code. In CI, cargo clippy -- -D warnings turns every warning into an error so nothing slips through.

Writing tests

Tests in Rust live in the same file as the code they test, inside a module that only compiles when testing. Add this to the bottom of src/main.rs:

Fig. 50rust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn counts_words_case_insensitively() {
        let counts = count_words("Rust rust RUST, cargo.");
        assert_eq!(counts["rust"], 3);
        assert_eq!(counts["cargo"], 1);
    }

    #[test]
    fn ignores_punctuation_only_tokens() {
        let counts = count_words("hello -- world");
        assert_eq!(counts.len(), 2);
    }
}

#[cfg(test)] is an attribute that says "only compile this when running tests", so test code never ends up in your release binary. mod tests declares a module. use super::* imports everything from the parent module, which is how the tests can call count_words. #[test] marks each test function, and assert_eq! compares two values and prints both if they differ, like expect(a).toBe(b).

Notice that the tests call count_words directly and don't touch the file system. Keeping the logic in a function that takes a string, and keeping file IO in main, is what made it easy to test. That's the same advice you'd get in any language, and Rust makes it natural.

Fig. 51bash
cargo test
Fig. 52text
   Compiling wordfreq v0.1.0 (/work/wordfreq)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 2.81s
     Running unittests src/main.rs (target/debug/build/wordfreq/1d6b4a9fb788fa6c/out/wordfreq-1d6b4a9fb788fa6c)

running 2 tests
test tests::ignores_punctuation_only_tokens ... ok
test tests::counts_words_case_insensitively ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Tests run in parallel by default, which is why their order in the output can change. To run a single test, pass part of its name: cargo test case_insensitively. Part 14 covers testing in depth, including testing web handlers without starting a server.

Shipping the binary

Build the release version:

Fig. 53bash
cargo build --release
Fig. 54text
-rwxr-xr-x 2 root root 531768 Nov 30 06:54 target/release/wordfreq

About 530 KB, including the colored crate and everything from the standard library this program uses. It needs no runtime. Copy it to another machine with the same OS and CPU architecture and it runs. Compare that to shipping a Node.js script, which needs Node installed at the right version plus a node_modules folder.

If you want to run it from anywhere on your own machine, cargo install --path . builds it in release mode and copies it into ~/.cargo/bin, which is already on your PATH. That's also how you install Rust tools other people have published, for example cargo install ripgrep.

Troubleshooting

These are the problems that come up most often in the first hour.

"cargo: command not found" or "'cargo' is not recognized"

Your terminal was open before the install finished, so it has an old PATH. Close it and open a new one. In VS Code, restart the whole editor. If it still fails, check that the Cargo bin folder is on your PATH: ~/.cargo/bin on macOS and Linux, %USERPROFILE%\.cargo\bin on Windows. On macOS and Linux, running . "$HOME/.cargo/env" fixes the current session.

"linker link.exe not found" on Windows

The MSVC build tools are missing or incomplete. Open the Visual Studio Installer, choose Modify on your install, and make sure "Desktop development with C++" is ticked, including a Windows SDK. Then open a new terminal.

"linker cc not found" on Linux

You need a C toolchain. Install build-essential on Debian and Ubuntu, gcc on Fedora, or base-devel on Arch.

"xcrun: error: invalid active developer path" on macOS

The command line tools are missing, often after a macOS upgrade removes them. Run xcode-select --install again.

rust-analyzer shows nothing or says it can't find a project

Open the folder that contains Cargo.toml, not a parent folder that contains several projects. If you want one VS Code window with several Rust projects, create a Cargo workspace (covered in part 6), or add each folder to rust-analyzer.linkedProjects in settings.

Builds feel slow

The first build of a project compiles every dependency, which is slow. Later builds only recompile what changed. Use cargo check while you work and keep full builds for when you want to run something. On Windows, see the Defender note above. On any OS, avoid putting projects in folders that sync to cloud storage like OneDrive or Dropbox, because they try to upload every file in target.

A crate fails to build with an error about OpenSSL

Some crates link to the system's OpenSSL. On Debian and Ubuntu install libssl-dev and pkg-config. On Fedora install openssl-devel. On macOS and Windows it's often easier to switch the crate to its rustls feature, which uses a pure-Rust TLS implementation. We'll do that in this series when we get to HTTP clients and databases.

What you learned and what comes next

You now have:

  1. Rust 1.100 (or newer) installed through rustup, with Clippy and rustfmt.
  2. An editor that shows types, errors and lints as you type.
  3. The full daily Cargo loop: new, check, run, build --release, add, fmt, clippy, test.
  4. A complete small program with error handling, a dependency and tests.
  5. A first look at things that will become familiar: immutable bindings, references with &, Result and match, closures, traits, and the last expression as the return value.

If you want to compare frameworks before we get to the web part, I wrote a comparison of Rust web frameworks covering Axum, Actix Web, Rocket and the others, including how each is hosted. It explains why this series uses Axum.

In part 2 we slow down and cover the everyday syntax properly: variables and shadowing, the number types and why there are so many, strings and why there are two kinds, functions, if as an expression, loops, and how all of it compares to TypeScript line by line. Keep the wordfreq project around. We will come back to it and make it better as the series goes on.