Chapter 17: Crates, Modules, and Packages

Effective source code organization is essential for building scalable, maintainable, and reusable software. Rust offers a powerful and structured module system that enables developers to encapsulate functionality, manage dependencies, and define visibility.

Relying on functions, header files, and global variables for organizing code, as the C language does, provides some structure but may result in name conflicts and unnecessary exposure of implementation details. Rust introduces more advanced concepts that enhance safety, clarity, and scalability, making it an excellent choice for larger and more complex projects.

This chapter explores the key components of Rust's modul system, including modules, visibility rules, crates, packages, and workspaces. While Cargo, Rust's build and dependency management tool, was briefly introduced earlier in the book, it will be covered comprehensively in a later chapter.

The three primary elements for Rust's code organization are:

  • Packages: The top-level abstraction in Cargo for organizing, building, and distributing crates.
  • Crates: Trees of modules that produce libraries or executables.
  • Modules: The foundational units for grouping functionality and hiding implementation details.

Rust's module system may seem complex at first, and some details in this chapter go beyond what beginners need to get started with Rust. Feel free to revisit this chapter later when working on larger or more structured projects.