Answer#
Cargo is installed with Rust (through rustup) and is the command you use for almost everything: creating projects, adding libraries (called crates), building, running, testing and publishing. You rarely call the compiler, rustc, by hand.
A project is a folder with a Cargo.toml file (its description and dependencies) and a src folder. Cargo also writes Cargo.lock, which pins the exact version of every dependency, and a target folder that holds everything it builds.
How to do it#
- Create a project. This also starts a Git repository in the folder unless it is already inside one.
cargo new helloThis is the Cargo.toml it writes with cargo 1.93.0:
[package]
name = "hello"
version = "0.1.0"
edition = "2024"
[dependencies]- Build and run it. The first command compiles in the fast-to-build debug profile;
target/debugholds the result.
cargo run Hello, world!- Run the tests (there are none yet, so the result is empty but passes).
cargo test- Add a dependency. The command edits
Cargo.tomlfor you and picks the newest compatible version.
cargo add serde_json- Check the code without producing a program. This is much faster than a build and reports the same errors.
cargo check- Build an optimised program for release. It is placed in
target/release.
cargo build --release| Command | What it does |
|---|---|
cargo new, cargo init | Create a project in a new or existing folder |
cargo check | Type-check without producing a program |
cargo build, cargo build --release | Compile (debug, or optimised) |
cargo run | Build, then run |
cargo test | Build and run the tests |
cargo add, cargo remove | Edit the dependency list |
cargo tree | Show the dependency graph |
cargo update | Move Cargo.lock to newer versions |
cargo clean | Delete the target folder |
Common mistakes#
- Committing the
targetfolder to Git. It is large and rebuildable; the.gitignorethatcargo newwrites already excludes it. - Forgetting
--releasewhen measuring speed. Debug builds are often many times slower. - Never cleaning old
targetfolders. Each project keeps its own, and they grow large over time.
In Ruststudio#
Ruststudio runs these commands for you from its menus and shows their output, and its Cargo Cleaner finds the target folders and cargo caches on your disk, with their size and age, and deletes only what you tick. See the Cargo Cleaner page.
Related questions#
What is the difference between Cargo.toml and Cargo.lock?#
Cargo.toml is what you write: the dependencies you want, with version ranges. Cargo.lock is what Cargo writes: the exact versions it chose. Commit Cargo.lock for programs so that every build uses the same versions.
What is a crate?#
A crate is one unit of Rust code that is compiled together: a library or a program. Libraries from crates.io are crates, and so is your own program.
Sources#
- The Cargo Book: https://doc.rust-lang.org/cargo/
- Cargo commands: https://doc.rust-lang.org/cargo/commands/index.html