Packages, Crates, and Modules
По мере роста кодовой базы ваших программ, организация кода будет получать всё большую важность. Группируя связанное и разделяя код по роду деятельности, вы делаете более понятным, где искать код, реализующий определённую задачу, и где нужно вносить правки, изменяющие поведение.
The programs we’ve written so far have been in one module in one file. As a project grows, you should organize code by splitting it into multiple modules and then multiple files. A package can contain multiple binary crates and optionally one library crate. As a package grows, you can extract parts into separate crates that become external dependencies. This chapter covers all these techniques. For very large projects comprising a set of interrelated packages that evolve together, Cargo provides workspaces, which we’ll cover in “Cargo Workspaces” in Chapter 14.
We’ll also discuss encapsulating implementation details, which lets you reuse code at a higher level: Once you’ve implemented an operation, other code can call 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.
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 имеет ряд механизмов, которые позволяют управлять организацией кода, в том числе управлять тем, какие детали доступны снаружи, какие детали скрыты, и какие имена есть в каждой области видимости в вашей программе. Эти механизмы, иногда обобщённо называемые системой модулей, включают в себя:
- 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
В этой главе мы рассмотрим всё перечисленное, обсудим их взаимодействие и объясним, как использовать их для управления областями видимости. К концу у вас должно появиться солидное понимание системы модулей и умение работать с областями видимости на уровне профессионала! (Примечание переводчика: материал этой главы может сломать вам мозг. Настоятельно рекомендуется самостоятельный поиск дополнительных материалов. Hang in there!)