Javatpoint Logo
Javatpoint Logo

Rust Modules

A module is a namespace which contains the definitions of the functions or its types. A module is a collection of items such as functions, structs, traits, impl blocks. By default, the modifier of the module is private, but it can be overridden with the public modifier by using pub keyword.

Following are the keywords used in the modules:

  • mod keyword: The "mod" keyword declares the new module.
  • pub keyword: By default, all the functions, types, modules and constants have a private visibility modifier. The pub keyword makes the visibility modifier as public, and therefore, they are accessible outside the namespace.
  • use keyword: The use keyword is used to import the module into local scope.

Module Definition

The module is defined by the mod keyword.

The syntax of Module:

A Module can be categorized in three ways:

1. Single module: When the module appeared in a single file is known as a single module.

Let's understand this through an example:

Output:

Single module

In the above example, module 'a' is defined, and every code defined in the block is inside the namespace 'a'. The function of module 'a' can be called by using the module name followed by namespace and then function name.

  • We can also do the above example by using a separate file:

Output:

Single module

In the above two examples, we examine that mod X is defined either in curly braces or in a separate file named as X.rs or X/mod.rs.

2. Sub-modules: In a single file, we can have multiple modules. Suppose the library name is "language" and it consists of two modules, i.e., C and Cplus.

Hierarchy of a "language" library is given below:


Rust Modules

Let's understand through an example:

Output:

C is a structured programming language
C++ is an object-oriented programming language

In the above example, the program consists of two modules, i.e., c and cplus and their respective functions are called by using c::c() and cplus::cplus().

3. Nested modules: Nested modules are those modules which consist of a module inside of modules, and they can be useful when the related modules are grouped together.

Let's understand this through an example:

Output:

a module
b module

In the above example, the program consists of two modules, i.e., 'a' and 'b' where 'b' is the inner module of 'a'. Both the modules consist the function with the same name but with different functionality. Both the functions are called by using a::a() and a::b::b() respectively. They both will not conflict with each other as they belong to different namespaces.


Next TopicRust Filesystem





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA