liveBook · Manning

Cargo

As explained in Learn Rust in a Month of Lunches

Cargo is Rust's package manager and build tool for creating, configuring, compiling, running, and managing Rust projects and their dependencies.

Cargo is Rust’s package manager and build tool. It gives projects a common structure and uses rustc to compile them, while taking care of the work needed to bring in external crates. A crate is a Rust project or a piece of code a project can use. section 18.1 section 18.1.1

A small Cargo project starts with a few commands:

  • Run `cargo new my_project` to create a project with `Cargo.toml` and `src/main.rs`. Add `--lib` if you want a library with `src/lib.rs` instead. section 18.1.1
  • Add an external crate under `[dependencies]` in `Cargo.toml`, or use a command such as `cargo add rand`. section 16.5.1
  • Run `cargo run` to build and run the program. Use `cargo build` to compile after adding a crate, so later builds can benefit from incremental compilation. section 18.1.1 section 18.1.2
[package]
name = "rust_book"
version = "0.1.0"
authors = ["David MacLeod"]
edition = "2021"
 
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
[dependencies]
rand = "0.8.5"

This `Cargo.toml` example puts `rand = "0.8.5"` under `[dependencies]`. Cargo uses that entry when building the project. section 16.5.1

Why use Cargo?

A standalone file can be compiled with `rustc test.rs`, but trying to use `rand` that way produces a missing-crate error. In a Cargo project, add `rand` as a dependency and run `cargo run`: Cargo compiles the needed crates before starting the program. On a later run, unchanged dependencies need not be recompiled. section 18.1.1 section 18.1.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Works through project creation, dependency setup, build commands, compiler output, and faster repeat builds.
Examples
Contrasts a missing-rand compiler error with a Cargo project that builds a random-letter program.
What it assumes
Assumes basic Rust code and a local Rust installation, but introduces Cargo commands through a simple project.
What you can do after
Operate/configure it: create a Rust project, add a crate, and build or run the result.
How it connects
Connects Cargo.toml, crates, dependencies, rustc, and incremental compilation.

Also explained in

Compare how 5 books explain Cargo →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.