17.5 Summary
Rust employs a structured, hierarchical system for code organization and dependency management, offering significant advantages over traditional C/C++ approaches, particularly regarding namespace control, visibility, and build consistency.
- Packages: The top-level unit managed by Cargo, defined by
Cargo.toml
. Packages contain source code, metadata, and dependencies, producing one or more crates. They are the unit of building, testing, and distribution. Workspaces group related packages. - Crates: The atomic unit of compilation (
rustc
). Each crate compiles into either a binary executable or a library. A package contains at least one (root) crate (lib.rs
ormain.rs
) and potentially others (src/bin/
). External dependencies are added as crates. - Modules: Used within a crate to organize code hierarchically (
mod
), control visibility (pub
,pub(crate)
, private by default), and create namespaces. Modules help structure code logically and enforce encapsulation.
This layered system promotes modularity, explicit dependencies, and clear API boundaries. By enforcing strict rules, such as the prevention of cyclic dependencies and default privacy, Rust encourages designs that are often more robust and maintainable than what might naturally arise in C or C++. While adapting from the .c
/.h
file model requires understanding these new concepts, the benefits in terms of project scalability, code clarity, and reduced build complexity typically become evident quickly.