Menu Close


Rust: Modules

As programs get larger, it’s necessary to spread them over more than one file and put functions and types in different namespaces. The Rust solution for both of these is modules. We call this component oriented architecture. 


Unlike other programming languages, a module do not represent a file. It represents something more. It is very similar to a “package” or a “namespace”. One Rust source file *.rs can contain one or more modules.

Each module can contain other modules inside. This will create a hierarchy. You can use two columns ::  as delimiter to identify a module component similar to URL that is using / as delimiter.

Example: module::sub-module::component-name

Public Module

You can use pub keyword to define public modules. This indicate that a module member can be used outside of module scope. You can use “*” to import all “pub” members defined into a module or you can specify each member to be imported by name. After import you can use the members as part of current scope. 


In this example modules are defined in a single file:


  • you can import elements of one module by keyword: use
  • you can access public elements of modules using ::
  • modules can be nested like Matryoshka dolls.

Homework: This example can be tested live: modules