Cargo — Rust's Package Manager & Build Tool
Cargo is npm + tsc + jest in one
Section titled “Cargo is npm + tsc + jest in one”If you have used npm (or yarn/pnpm), Cargo will feel immediately familiar. It manages dependencies, builds your project, runs your code, and runs your tests — all under one roof.
Creating a new project
Section titled “Creating a new project”# Node / TypeScriptmkdir my-app && cd my-appnpm init -ynpm install typescript --save-dev
# Rustcargo new my-app # creates a binary (has fn main)cargo new my-lib --lib # creates a library (no fn main)cd my-appcargo new creates:
flowchart TD root["my-app/"] --> toml["Cargo.toml — like package.json"] root --> lock["Cargo.lock — like package-lock.json"] root --> src["src/"] src --> main["main.rs — entry point"]
Cargo.toml vs package.json
Section titled “Cargo.toml vs package.json”// package.json{ "name": "my-app", "version": "1.0.0", "dependencies": { "express": "^4.18.0" }, "devDependencies": { "typescript": "^5.0.0", "@types/express": "^4.17.0" }}# Cargo.toml[package]name = "my-app"version = "0.1.0"edition = "2021"
[dependencies]axum = "0.7"tokio = { version = "1", features = ["full"] }serde = { version = "1", features = ["derive"] }
[dev-dependencies]# test-only crates go hereAdding dependencies
Section titled “Adding dependencies”# npmnpm install serde_json # runtime depnpm install --save-dev vitest # dev dep
# Cargocargo add serde_json # runtime depcargo add --dev pretty_assertions # dev depcargo add updates Cargo.toml automatically, exactly like npm install.
Core subcommands
Section titled “Core subcommands”cargo build # compile (debug, fast, unoptimized)cargo build --release # compile (optimized, slower build)cargo run # compile + executecargo run -- --port 8080 # pass args to your binarycargo check # type-check only, no binary (very fast)cargo test # run all testscargo test my_fn # run tests whose name contains "my_fn"cargo doc --open # generate + open HTML docscargo clean # delete target/ directoryCargo.lock — commit it or not?
Section titled “Cargo.lock — commit it or not?”# Binary / application → COMMIT Cargo.lock (reproducible builds)# Library crate → DO NOT commit Cargo.lock (let consumers pick versions)This mirrors npm’s convention: applications commit package-lock.json; published libraries typically do not.