As you delve deeper into the world of programming, particularly in large-scale projects, the organization of your code becomes increasingly crucial. By grouping related functionalities and separating code with distinct features, you can streamline the process of locating specific code implementations and modifying feature functionalities.
Single Module to Multiple Files
In the initial stages of programming, we often confine our code to a single module in one file. However, as a project expands, it becomes necessary to organize the code by dividing it into multiple modules and subsequently, multiple files. A package in this context can encompass multiple binary crates and optionally, one library crate. As the package continues to grow, you can extract parts into separate crates that eventually become external dependencies.
Public Interface and Implementation Details
Once you've implemented an operation, other code can interact with your code via its public interface without having to know how the implementation works. The way you write code defines which parts are public for other code to use and which parts are private implementation details that you reserve the right to change. This is another way to limit the amount of detail you have to keep in your head.
Scope
A related concept is scope: the nested context in which code is written has a set of names that are defined as “in scope.” When reading, writing, and compiling code, programmers and compilers need to know whether a particular name at a particular spot refers to a variable, function, struct, enum, module, constant, or other item and what that item means. You can create scopes and change which names are in or out of scope. You can’t have two items with the same name in the same scope; tools are available to resolve name conflicts.
Rust's Module System
Rust has a number of features that allow you to manage your code’s organization, including which details are exposed, which details are private, and what names are in each scope in your programs. These features, sometimes collectively referred to as the module system, include:
- Packages: A Cargo feature that lets you build, test, and share crates
- Crates: A tree of modules that produces a library or executable
- Modules and use: Let you control the organization, scope, and privacy of paths
- Paths: A way of naming an item, such as a struct, function, or module