Module 0 · Orientation & tooling
0.2Tooling, Cargo & project layout
How rustup, Cargo and Cargo.toml line up with the tools you already use, which cargo command to run when, and how to read a compiler error.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| Installing the toolchain | The Node.js installer, or a version manager such as nvm or Volta | The .NET SDK installer | rustup, which installs and updates rustc, cargo, clippy and rustfmt |
| Build tool and package manager | npm or pnpm, plus tsc | The dotnet CLI and NuGet | cargo does both |
| Project file | package.json and tsconfig.json | MyApp.csproj | Cargo.toml |
| Lock file | package-lock.json or pnpm-lock.yaml | packages.lock.json (opt-in) | Cargo.lock |
| Package registry | npmjs.com | nuget.org | crates.io |
| Linter and formatter | ESLint and Prettier | Roslyn analyzers and dotnet format | cargo clippy and cargo fmt, installed with Rust |
In TypeScript you juggle Node, a package manager, tsc, a test runner, a linter and a formatter, each with its own config file. Rust has one tool for all of it:.NET folds most of your tooling into the dotnet CLI. Rust goes further: Cargo creates projects, fetches packages, builds, runs, tests, lints and formats, and everyone uses it the same way. This lesson sets it up and shows which command to run when.
Installing Rust with rustup
rustup installs Rust and keeps it up to date, like Volta or nvm for Node: it plays the part of the .NET SDK installer. It installs these four tools, among others: rustc (the compiler), cargo (the build tool), clippy (the linter) and rustfmt (the formatter).
# macOS and Linux (see rustup.rs for the current command)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Windows: run rustup-init.exe from rustup.rs, or
winget install Rustlang.Rustup
# Check it worked, and update later
cargo --version
rustup update
On Windows, Rust uses Microsoft’s C++ linker, so the installer also offers to install the Visual Studio C++ Build Tools. Say yes unless you already have them.
For your editor, install the rust-analyzer extension (VS Code and most other editors support it), or use JetBrains RustRover. Either gives you completion, inline types and errors as you type, like the TypeScript language serviceRoslyn.
A new stable Rust ships every six weeks, and updates are designed not to break code that compiled before. Bigger language changes come in editions (2015, 2018, 2021, 2024). Each project picks its edition in Cargo.toml, a bit like <LangVersion> in a .csproj, but projects on different editions still work together. This site uses edition 2024.
Your first project
cargo new is npm init plus tsc --initdotnet new console:
cargo new hello
cd hello
cargo run
It creates this layout, and also runs git init if you’re not already inside a repository:
hello/
├── .gitignore ignores target/
├── Cargo.toml the project file
└── src/
└── main.rs the program
The program it generates is the usual first one:
console.log("Hello, world!");Console.WriteLine("Hello, world!");fn main() {
println!("Hello, world!");
}Output
Hello, world!
cargo run compiles the project, puts the executable in target/debug/, and runs it. The target/ folder holds all build output, like dist/ in a TypeScript projectbin/ and obj/ in .NET. It’s safe to delete.
Cargo.toml and Cargo.lock
Cargo.toml is your package.json.csproj. Here’s a fresh one with one dependency added:
[package]
name = "hello"
version = "0.1.0"
edition = "2024"
[dependencies]
serde = { version = "1", features = ["derive"] }
Here’s how package.json declares one:
{
"name": "hello",
"version": "0.1.0",
"dependencies": {
"zod": "^4.0.0"
}
}
Here’s how a .csproj declares one:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
</Project>
You rarely edit [dependencies] by hand. cargo add does it for you, like npm installdotnet add package:
cargo add serde --features derive
Packages are called crates and come from crates.io. Their documentation is generated automatically at docs.rs.
Cargo.lock records the exact version of every crate in the build, like package-lock.jsonNuGet’s opt-in packages.lock.json. Cargo writes it on the first build. Commit it, so everyone on the team and your CI build the same versions.
Cargo also has features (optional parts of a crate you switch on, like derive above) and workspaces (several crates in one repository, like a pnpm workspacea .sln). Module 7 covers both.
The everyday commands
You’ll run these all day:
cargo check # type-check and borrow-check only: the fastest feedback
cargo build # debug build into target/debug/
cargo build --release # optimized build into target/release/
cargo run # build (debug) and run
cargo run -- --verbose # arguments after -- go to your program
cargo test # build and run the tests
cargo clippy # lint: hundreds of checks for bugs and unidiomatic code
cargo fmt # format every file with rustfmt
cargo doc --open # build HTML docs for your code and its dependencies
Tests don’t need a framework package or a separate test project. A test is a function marked #[test], usually in a tests module at the bottom of the file it tests:
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
println!("{}", add(2, 3));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_two_numbers() {
assert_eq!(add(2, 3), 5);
}
}#[cfg(test)] means “compile this only when testing”, so the tests aren’t in your release build. Module 13 covers tests in depth.
Reading compiler errors
Rust’s compiler errors are long because they’re trying to help. Here’s a common one: changing a variable that wasn’t declared as changeable.
let total = 0;
total += 5;
println!("{total}");Rust doesn't compile this: error E0384
error[E0384]: cannot assign twice to immutable variable `total` --> main.rs:2:1 | 1 | let total = 0; | ----- first assignment to `total` 2 | total += 5; | ^^^^^^^^^^ cannot assign twice to immutable variable | help: consider making this binding mutable | 1 | let mut total = 0; | +++
Read it from the top:
- The code and summary.
error[E0384]is the error code, followed by one line saying what’s wrong. Runrustc --explain E0384for a longer explanation with examples, or search the code online. - The location. The
-->line gives the file, line and column, like a TypeScriptC# error. - The labels. The source is printed with
^and-marks under the parts that matter, each with a short note. Many errors point at more than one place: here, both the declaration and the assignment. - The help. A
help:line often suggests the fix, here addingmut. Your editor offers these as quick fixes. For warnings,cargo fixandcargo clippy --fixcan apply the suggestions that are safe to apply automatically.
Warnings use the same layout. Cargo prints them but still builds, so read them: unused variables and unneeded mut are often a sign of a real mistake.
Project layout
As a project grows, Cargo finds files by convention, so there’s nothing to register in Cargo.toml:
hello/
├── Cargo.toml
├── Cargo.lock
├── src/
│ ├── main.rs the program's entry point (fn main)
│ ├── lib.rs the library: code other crates, tests and main.rs can use
│ └── bin/
│ └── tool.rs an extra executable: cargo run --bin tool
├── tests/ integration tests, which use the library like an outside caller
├── examples/ small programs that show how to use the library: cargo run --example name
└── target/ build output (not committed)
src/main.rsmakes the package a program, like the entry file you run withnodea console app’sProgram.cs.src/lib.rsmakes it a library, like a package’sindex.tsa class library project.- A package can have both. Then
main.rsstays small and calls the library by the package name, for examplehello::run(), which also makes the logic easy to test.
Mental model shiftPackage, crate, module
A package is a folder with a Cargo.toml, like an npm packagea project. A crate is one thing the compiler builds from it: a library or an executable, like a .NET assembly. A module is a namespace inside a crate, like a TypeScript modulea C# namespace. Module 7 covers modules and crates.
Which one should I use?
Cargo has one command for each job. The mapping to what you already use:
| What | When | Why | How |
|---|---|---|---|
cargo check | While you write code, to see if it compiles. Your editor runs it for you through rust-analyzer. | It runs the type and borrow checks but skips generating machine code, so it’s much faster than a build. | Like tsc --noEmit..NET has no check-only build; dotnet build is closest. |
cargo run | To try the program while developing. | Builds only what changed, then runs it in one step. | Like node or tsx.Like dotnet run. Pass arguments after --. |
cargo build | When you need the executable but don’t want to run it yet. | Compiles quickly: an unoptimized debug build with extra runtime checks, such as integer overflow. | Like tsc.Like dotnet build. Output in target/debug/. |
cargo build --release | To ship, deploy or measure speed. | Turns on full optimization. Builds take longer, and the program runs much faster. | Like a production bundle.Like dotnet publish. Output in target/release/. |
cargo test | After every change worth keeping, and in CI. | Runs unit tests, integration tests in tests/ and, for libraries, the examples in doc comments. | Like npm test.Like dotnet test. cargo test name runs matching tests only. |
cargo clippy | Before you commit, and in CI. | Catches bugs and unidiomatic code that compiles fine. Its suggestions teach you idiomatic Rust. | Like ESLint.Like Roslyn analyzers. Use cargo clippy -- -D warnings in CI to fail on warnings. |
cargo fmt | Before you commit, or on save in your editor. | There’s one standard style, so nobody argues about formatting. | Like Prettier.Like dotnet format. Use cargo fmt --check in CI. |
cargo add | To add a dependency. | Finds the latest version and edits Cargo.toml for you. | Like npm install zod.Like dotnet add package. |
Rule of thumb: let your editor run cargo check as you type, use cargo run to try things, and run cargo fmt, cargo clippy and cargo test before every commit. Use --release only when you ship or measure performance. A good CI pipeline is those three commands with warnings as errors: cargo fmt --check, cargo clippy -- -D warnings, cargo test.
Under the hood
When you run cargo build, Cargo:
- Reads
Cargo.tomlandCargo.lockand works out every crate the build needs. - Downloads any missing crates as source code into a cache in your home folder (
~/.cargo/registry), shared by all your projects. There’s no per-projectnode_modules.Unlike NuGet packages, crates don’t ship prebuilt DLLs. - Compiles each dependency once with
rustcand caches the result intarget/. This is why the first build of a project is slow and later builds are fast. - Compiles your crate, reusing work from the last build where it can.
- Links everything into one executable. Your dependencies are compiled into it, so you deploy one file, with no runtime to install: no Node.js.NET runtime. It still uses the system’s C runtime. On Linux and macOS that’s always there; on Windows it’s the Visual C++ runtime (
vcruntime140.dll), which most machines have and which you can link statically instead.
The difference between debug and release builds comes from profiles, which you can tune in Cargo.toml:
[profile.dev]
opt-level = 0 # the default: no optimization, fastest to compile
[profile.release]
opt-level = 3 # the default: full optimization
lto = true # optional: optimize across crates, for a smaller, faster binary
Debug builds also keep runtime checks that release builds turn off, such as panicking on integer overflow. Primitive types are covered in the next module.
Common pitfalls
Common pitfallArguments go after --
cargo run --verbose passes --verbose to Cargo, not to your program. Put your program’s arguments after --: cargo run -- --verbose. It’s the same rule as npm run start -- --verbosedotnet run -- --verbose.
Common pitfallA version is a range, not a pin
serde = "1.0.200" in Cargo.toml means “1.0.200 or any later 1.x”, like ^1.0.200 in npm, and Cargo picks the newest version that matches. That may surprise you: NuGet also reads Version="1.0.200" as a minimum, but it restores the lowest version that matches, so you get 1.0.200 itself. Cargo.lock pins the exact version Cargo picked, until you run cargo update. To require one exact version, write "=1.0.200", but that’s rarely a good idea in a library.
Common pitfallDon't benchmark a debug build
cargo run gives you an unoptimized build. It can be many times slower than the release build, so timings from it say nothing about Rust’s speed. Use cargo run --release whenever you measure.
Common pitfallClippy warnings don't fail the build
By default, cargo clippy and cargo build print warnings and still succeed, so warnings pile up unnoticed. In CI, run cargo clippy -- -D warnings so any warning fails the build.
Try it yourself
Exercise: port this to Rust
Create a project with cargo new greet and port this program into src/main.rs. It greets the name given as the first command-line argument, or world if there isn’t one. Then run cargo clippy, cargo fmt and cargo run -- Ada.
const name = process.argv[2] ?? "world";
console.log(`Hello, ${name}!`);var name = args.Length > 0 ? args[0] : "world";
Console.WriteLine($"Hello, {name}!");Expected output
Hello, world!
Show a hint
std::env::args() returns the program name first and then the arguments. Call .nth(1) to get the first argument, which gives you an Option. Then call .unwrap_or_else with a closure that returns the default String.
Show a solution
fn main() {
let name = std::env::args()
.nth(1)
.unwrap_or_else(|| String::from("world"));
println!("Hello, {name}!");
}std::env::args() lists the program itself first, then its arguments: index 0 is the program and index 1 is the first argument. nth(1) returns an Option, Rust's way of saying a value may be missing, which Module 6 covers. Run cargo run -- Ada and it prints Hello, Ada!
Saved in this browser only.