liveBook · Manning

Cargo

As explained in Rust in Action: Systems programming concepts and techniques

Cargo is Rust's package manager and build system for creating, compiling, running, documenting, and managing Rust projects.

Cargo is Rust’s package manager and build system. It creates projects, manages dependencies, and drives the Rust compiler, rustc, to build executable programs. section 1.3.1 section 2.1.2

With Rust installed, create and run a first project from a command prompt: section 1.3.1

$ cargo new hello
$ cd hello
$ cargo run

These commands create the hello project, enter its directory, and run its starter program. section 1.3.1

The new project has a Cargo.toml file for metadata, including its name, version, and dependencies. Its source code is in src/main.rs. When you run the project, Cargo compiles the starter program in debug mode and executes it; the executable is placed under target/debug. section 1.3.1 section 2.1.2

Useful Cargo commands include:

  • cargo new creates a project in a new directory; cargo init initializes one in the current directory. section 1.6.2
  • cargo build downloads dependencies and compiles the code. cargo run builds and then runs the executable. section 1.6.2
  • cargo doc builds HTML documentation for the current project’s dependencies. section 1.6.2
  • cargo run -v shows more detail, including how Cargo invokes rustc. section 2.1.2

Add a dependency

For a search project, run cargo new grep-lite --vcs none and cd grep-lite. Then run cargo add regex@1 to add version 1 of the regex crate to Cargo.toml, followed by cargo build to download and compile it. If cargo add is unavailable, it may need separate installation. section 2.11 section 9.6.4

Some projects need a particular compiler toolchain. For a project that requires nightly Rust, install it with rustup and use cargo +nightly run to select it. section 12.9.4

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Walks through project creation, building, dependencies, and verbose compiler output without detailing Cargo’s implementation.
Examples
Uses a Hello World project, a regex search project, and a clock application to demonstrate Cargo workflows.
What it assumes
Starts with Rust installed and a command prompt, then creates a runnable project without requiring prior Rust code.
What you can do after
Apply it via Cargo to create, build, run, and add dependencies to Rust projects.
How it connects
Connects package management and crates to rustc compilation and rustup toolchain selection.

Also explained in

Compare how 6 books explain Cargo →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.