|
1 | 1 | # Modules
|
2 | 2 |
|
3 |
| -> **<sup>Syntax:<sup>**\ |
| 3 | +> **<sup>Syntax:</sup>**\ |
4 | 4 | > _Module_ :\
|
5 | 5 | > `mod` [IDENTIFIER] `;`\
|
6 | 6 | > | `mod` [IDENTIFIER] `{`\
|
@@ -40,21 +40,26 @@ struct, enumeration, union, type parameter or crate can't shadow the name of a
|
40 | 40 | module in scope, or vice versa. Items brought into scope with `use` also have
|
41 | 41 | this restriction.
|
42 | 42 |
|
43 |
| -A module without a body is loaded from an external file, by default with the |
44 |
| -same name as the module, plus the `.rs` extension. When a nested submodule is |
45 |
| -loaded from an external file, it is loaded from a subdirectory path that |
46 |
| -mirrors the module hierarchy. |
47 |
| - |
48 |
| -```rust,ignore |
49 |
| -// Load the `vec` module from `vec.rs` |
50 |
| -mod vec; |
51 |
| -
|
52 |
| -mod thread { |
53 |
| - // Load the `local_data` module from `thread/local_data.rs` |
54 |
| - // or `thread/local_data/mod.rs`. |
55 |
| - mod local_data; |
56 |
| -} |
57 |
| -``` |
| 43 | +A module without a body is loaded from an external file. By default, the path |
| 44 | +to the file mirrors the logical [module path]. Ancestor path components are |
| 45 | +directories, and the module's contents are in a file with the name of the |
| 46 | +module plus the `.rs` extension. For example, the following module structure |
| 47 | +can have this corresponding filesystem structure: |
| 48 | + |
| 49 | +Module Path | Filesystem Path | File Contents |
| 50 | +--------------------- | --------------- | ------------- |
| 51 | +`crate` | `lib.rs` | `mod util;` |
| 52 | +`crate::util` | `util.rs` | `mod config;` |
| 53 | +`crate::util::config` | `util/config.rs` | |
| 54 | + |
| 55 | +> **Note**: Module filenames may also be the name of the module as a directory |
| 56 | +> with the contents in a file named `mod.rs` within that directory. Previous |
| 57 | +> to Rust 1.30, this was the way to load a module with nested children. The |
| 58 | +> above example can alternately be expressed with `crate::util`'s contents in |
| 59 | +> a file named `util/mod.rs`. It is not allowed to have both `util.rs` and |
| 60 | +> `util/mod.rs`. It is encouraged to use the new naming convention as it is |
| 61 | +> more consistent, and avoids having many files named `mod.rs` within a |
| 62 | +> project. |
58 | 63 |
|
59 | 64 | The directories and files used for loading external file modules can be
|
60 | 65 | influenced with the `path` attribute.
|
@@ -94,5 +99,6 @@ The built-in attributes that have meaning on a function are [`cfg`],
|
94 | 99 | [IDENTIFIER]: identifiers.html
|
95 | 100 | [attribute]: attributes.html
|
96 | 101 | [items]: items.html
|
| 102 | +[module path]: paths.html |
97 | 103 | [prelude]: crates-and-source-files.html#preludes-and-no_std
|
98 | 104 | [the lint check attributes]: attributes.html#lint-check-attributes
|
0 commit comments