Chapter 23: Working with Cargo

Cargo is Rust’s official build system and package manager, integral to the Rust development experience. It streamlines essential tasks such as creating new projects, managing dependencies, compiling code, running tests, and publishing packages to the central registry, Crates.io. While previous chapters introduced basic Cargo usage for building and running code (Chapter 4) and managing dependencies (Chapter 17), this chapter delves deeper.

We will explore Cargo’s command-line interface (CLI), the standard project structure it encourages (often managed with version control systems like Git), dependency version management, and the distinction between building libraries and binary applications. Further topics include publishing your own packages, customizing build configurations (profiles), organizing larger projects with workspaces, and generating project documentation.

Cargo is a powerful tool with many features; this chapter focuses on the capabilities most relevant for developers, particularly those coming from C or C++ backgrounds where build systems (like Make or CMake) and package managers (like Conan or vcpkg) are often separate entities. For exhaustive details, refer to the official Cargo Book.

Note that Cargo’s testing and benchmarking features (cargo test, cargo bench) are covered in the next chapter.

A brief note on terminology: In Rust, the terms crate and package are often used interchangeably in common conversation, but they have distinct meanings in the context of Cargo. A package is a unit that Cargo builds, publishes, and downloads. It contains a Cargo.toml file (the manifest) and one or more crates. A package must contain at least one library crate or one binary crate. It can contain a library crate and multiple binary crates. Crates are the fundamental units of compilation (a library crate or a binary crate). When people refer to downloading a dependency from Crates.io, they are technically downloading a package, although it is common to hear this referred to as downloading a “crate”. Since most library packages contain only a single library crate, using “crate” when “package” is meant is often not significantly misleading. The term project is also often used synonymously with package, particularly when referring to the directory structure created by cargo new. This chapter will use the terms package and crate more precisely where the distinction is relevant, but acknowledge the common community usage.