Home » Rust Module Filesystem

Filesystem

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.

Filename: src/lib.rs

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:

Rust Filesystem

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.

  • mod A; looks like:

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.

Filename: src/A.rs.

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.

Filename: src/lib.rs

  • mod B; looks like:

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.

Filename: src/B.rs

Now we will extract the module C from the file src/B.rs and replace the body of the module C with the semicolon.

  • mod C; looks like:

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:

  • If the module named “server” and has no submodules, then all the declarations of the module can be placed in the file server.rs.
  • If the module named “server” contains the submodules, then all the declarations of the module are to be placed in the file server/mod.rs.

You may also like