A module forms a hierarchical structure so that the project becomes more understandable. Rust module system is used to split the multiple files in such a way that not everything lies in the src/lib.rs or src/main.rs file.
In the above example, a program consists of three modules, i.e., A,B and C. C is an inner module of a B module.
Module hierarchy of a given file is:
If the module contains many functions and the functions are very lengthy, then it becomes difficult to find the code of a particular function. Rust provides the flexibility by providing the module system. We can have a separate file of each module rather than placing in the same file, i.e., src/lib.rs.
Steps to be followed:
Firstly, replace the block of a module 'A' with a semicolon.
The semicolon ; tells the Rust to find the definition of a module 'A' into another location where the scope of module 'A' is defined.
Now create the external file which contains the definition of module A. The name of the external file would be named as src/A.rs. After creating the file, write the definition of module A in this file which has been removed previously.
In this case, we do not need to write the mod declaration as we mentioned in the src/lib.rs file. And, if we write the mod declaration here, then it becomes a submodule of module A.
Rust bydefault looks into the src/lib.rs file then this file determines which file is to be looked further.
Now, we will extract the module B from the file src/lib.rs and replace the body of module B with the semicolon.
Now create the external file which contains the definition of module B. The name of the external file would be named as src/B.rs. After creating the file, write the definition of module B in this file which have been removed previously.
Now we will extract the module C from the file src/B.rs and replace the body of the module C with the semicolon.
Now create the external file which contains the definition of module C. The name of the external file would be named as src/C.rs. After creating the file, write the definition of module C in this file which has been removed previously.
File name: src/C.rs
Note: The extraction of module C from the module B will cause the compilation error as src/B.rs is different from the src/lib.rs. Therefore, the src/B.rs is to be moved to a new directory and renamed as src/B/mod.rs, then move the submodule into the new 'B' directory.
Rules of Module filesystem: