The naming conventions for Rust modules follow a clear community consensus and engineering practices, primarily consisting of the following core principles:
1. Basic Naming Style:Snake Case (snake_case)
- Rule: All module names must use all lowercase letters, with words separated by underscores
<span>_</span>(for example:<span>network_utils</span>,<span>user_authentication</span>). - Prohibited:
- Camel Case (e.g.,
<span>NetworkUtils</span>❌) - Kebab Case (e.g.,
<span>network-utils</span>❌) - Abbreviations (e.g.,
<span>net_util</span>not recommended unless the abbreviation is widely known, such as<span>http</span>).
2. Functionally Descriptive Naming: Reflecting Module Responsibilities
- By Function/Business Division: Module names should directly reflect the functionality or business logic they encapsulate, rather than the type of code. Examples: ✅
<span>order::create</span>(Order Creation) ✅<span>payment::processor</span>(Payment Processing) ❌<span>models</span>(vague),<span>utils</span>(too generalized). - Utility Modules: General utilities (such as date handling, encryption) should be placed in separate modules (e.g.,
<span>utils::date</span>), avoiding coupling with business logic.
3. Naming Practices to Avoid
- Redundant Suffixes: Prohibited from adding
<span>_rs</span>,<span>_mod</span>and other redundant identifiers (e.g.,<span>network_rs</span>❌). - Single Letter Words: Except for the last part, words in module names cannot be single letters (✅
<span>btree_map</span>, ❌<span>b_tree_map</span>). - Generic Names: Avoid using names like
<span>common</span>,<span>misc</span>that lack clear meaning.
4. Module Hierarchy and File Mapping
- File Structure:
- Single File Module:
<span>mod network;</span>corresponds to<span>network.rs</span>file. - Multi-file Module: The directory
<span>network/</span>must contain an entry file (<span>mod.rs</span>or<span>network.rs</span>), with submodules exported through the entry file. - Nested Modules: Deep modules must be declared stepwise through parent modules, keeping the path clear (e.g.,
<span>crate::api::v1::user</span>). - Visibility Control: Modules are private by default, exposed for external use through
<span>pub mod</span>.
Summary: Core Specification Quick Reference
| Specification Type | Correct Example | Incorrect Example |
|---|---|---|
| Naming Style | <span>user_management</span> |
<span>UserManagement</span> |
| Functionally Descriptive | <span>auth::oauth2</span> |
<span>auth_utils</span> |
| File Mapping | <span>mod.rs</span> or <span>auth.rs</span> |
<span>auth-module.rs</span> |
| Hierarchy Depth | <span>api::v1::user</span> |
<span>apiv1user</span> |
Following the above specifications can significantly enhance code readability, collaboration efficiency, and long-term maintainability, aligning with Rust community standards (such as <span>rustfmt</span> and <span>clippy</span> toolchain).